1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
5 * GLib is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * GLib is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with GLib; see the file COPYING.LIB. If not,
17 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
34 g_markup_error_quark (void)
36 static GQuark error_quark = 0;
39 error_quark = 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,
65 struct _GMarkupParseContext
67 const GMarkupParser *parser;
69 GMarkupParseFlags flags;
75 GDestroyNotify dnotify;
77 /* A piece of character data or an element that
78 * hasn't "ended" yet so we haven't yet called
79 * the callback for it.
81 GString *partial_chunk;
83 GMarkupParseState state;
90 const gchar *current_text;
91 gssize current_text_len;
92 const gchar *current_text_end;
94 GString *leftover_char_portion;
96 /* used to save the start of the last interesting thingy */
101 guint document_empty : 1;
107 * g_markup_parse_context_new:
108 * @parser: a #GMarkupParser
109 * @flags: one or more #GMarkupParseFlags
110 * @user_data: user data to pass to #GMarkupParser functions
111 * @user_data_dnotify: user data destroy notifier called when the parse context is freed
113 * Creates a new parse context. A parse context is used to parse
114 * marked-up documents. You can feed any number of documents into
115 * a context, as long as no errors occur; once an error occurs,
116 * the parse context can't continue to parse text (you have to free it
117 * and create a new parse context).
119 * Return value: a new #GMarkupParseContext
121 GMarkupParseContext *
122 g_markup_parse_context_new (const GMarkupParser *parser,
123 GMarkupParseFlags flags,
125 GDestroyNotify user_data_dnotify)
127 GMarkupParseContext *context;
129 g_return_val_if_fail (parser != NULL, NULL);
131 context = g_new (GMarkupParseContext, 1);
133 context->parser = parser;
134 context->flags = flags;
135 context->user_data = user_data;
136 context->dnotify = user_data_dnotify;
138 context->line_number = 1;
139 context->char_number = 1;
141 context->partial_chunk = NULL;
143 context->state = STATE_START;
144 context->tag_stack = NULL;
145 context->attr_names = NULL;
146 context->attr_values = NULL;
147 context->cur_attr = -1;
148 context->alloc_attrs = 0;
150 context->current_text = NULL;
151 context->current_text_len = -1;
152 context->current_text_end = NULL;
153 context->leftover_char_portion = NULL;
155 context->start = NULL;
156 context->iter = NULL;
158 context->document_empty = TRUE;
159 context->parsing = FALSE;
161 context->balance = 0;
167 * g_markup_parse_context_free:
168 * @context: a #GMarkupParseContext
170 * Frees a #GMarkupParseContext. Can't be called from inside
171 * one of the #GMarkupParser functions.
175 g_markup_parse_context_free (GMarkupParseContext *context)
177 g_return_if_fail (context != NULL);
178 g_return_if_fail (!context->parsing);
180 if (context->dnotify)
181 (* context->dnotify) (context->user_data);
183 g_strfreev (context->attr_names);
184 g_strfreev (context->attr_values);
186 g_slist_foreach (context->tag_stack, (GFunc)g_free, NULL);
187 g_slist_free (context->tag_stack);
189 if (context->partial_chunk)
190 g_string_free (context->partial_chunk, TRUE);
192 if (context->leftover_char_portion)
193 g_string_free (context->leftover_char_portion, TRUE);
199 mark_error (GMarkupParseContext *context,
202 context->state = STATE_ERROR;
204 if (context->parser->error)
205 (*context->parser->error) (context, error, context->user_data);
209 set_error (GMarkupParseContext *context,
219 va_start (args, format);
220 s = g_strdup_vprintf (format, args);
223 tmp_error = g_error_new (G_MARKUP_ERROR,
225 _("Error on line %d char %d: %s"),
226 context->line_number,
227 context->char_number,
232 mark_error (context, tmp_error);
234 g_propagate_error (error, tmp_error);
238 is_name_start_char (gunichar c)
240 if (g_unichar_isalpha (c) ||
249 is_name_char (gunichar c)
251 if (g_unichar_isalnum (c) ||
263 char_str (gunichar c,
267 g_unichar_to_utf8 (c, buf);
272 utf8_str (const gchar *utf8,
275 char_str (g_utf8_get_char (utf8), buf);
280 set_unescape_error (GMarkupParseContext *context,
282 const gchar *remaining_text,
283 const gchar *remaining_text_end,
291 gint remaining_newlines;
294 remaining_newlines = 0;
296 while (p != remaining_text_end)
299 ++remaining_newlines;
303 va_start (args, format);
304 s = g_strdup_vprintf (format, args);
307 tmp_error = g_error_new (G_MARKUP_ERROR,
309 _("Error on line %d: %s"),
310 context->line_number - remaining_newlines,
315 mark_error (context, tmp_error);
317 g_propagate_error (error, tmp_error);
323 USTATE_AFTER_AMPERSAND,
324 USTATE_INSIDE_ENTITY_NAME,
325 USTATE_AFTER_CHARREF_HASH
329 unescape_text (GMarkupParseContext *context,
331 const gchar *text_end,
335 #define MAX_ENT_LEN 5
340 gboolean normalize_attribute;
342 str = g_string_new (NULL);
344 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
345 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
346 normalize_attribute = TRUE;
348 normalize_attribute = FALSE;
350 state = USTATE_INSIDE_TEXT;
353 while (p != text_end && context->state != STATE_ERROR)
355 g_assert (p < text_end);
359 case USTATE_INSIDE_TEXT:
361 while (p != text_end && *p != '&')
363 if ((*p == '\t' || *p == '\n') && normalize_attribute)
365 g_string_append_len (str, start, p - start);
366 g_string_append_c (str, ' ');
367 p = g_utf8_next_char (p);
372 g_string_append_len (str, start, p - start);
373 g_string_append_c (str, normalize_attribute ? ' ' : '\n');
374 p = g_utf8_next_char (p);
376 p = g_utf8_next_char (p);
380 p = g_utf8_next_char (p);
385 g_string_append_len (str, start, p - start);
390 if (p != text_end && *p == '&')
392 p = g_utf8_next_char (p);
393 state = USTATE_AFTER_AMPERSAND;
398 case USTATE_AFTER_AMPERSAND:
402 p = g_utf8_next_char (p);
405 state = USTATE_AFTER_CHARREF_HASH;
407 else if (!is_name_start_char (g_utf8_get_char (p)))
411 set_unescape_error (context, error,
413 G_MARKUP_ERROR_PARSE,
414 _("Empty entity '&;' seen; valid "
415 "entities are: & " < > '"));
421 set_unescape_error (context, error,
423 G_MARKUP_ERROR_PARSE,
424 _("Character '%s' is not valid at "
425 "the start of an entity name; "
426 "the & character begins an entity; "
427 "if this ampersand isn't supposed "
428 "to be an entity, escape it as "
436 state = USTATE_INSIDE_ENTITY_NAME;
442 case USTATE_INSIDE_ENTITY_NAME:
444 gchar buf[MAX_ENT_LEN+1] = {
445 '\0', '\0', '\0', '\0', '\0', '\0'
449 while (p != text_end)
453 else if (!is_name_char (*p))
457 set_unescape_error (context, error,
459 G_MARKUP_ERROR_PARSE,
460 _("Character '%s' is not valid "
461 "inside an entity name"),
466 p = g_utf8_next_char (p);
469 if (context->state != STATE_ERROR)
484 /* move to after semicolon */
485 p = g_utf8_next_char (p);
487 state = USTATE_INSIDE_TEXT;
489 if (strcmp (buf, "lt") == 0)
490 g_string_append_c (str, '<');
491 else if (strcmp (buf, "gt") == 0)
492 g_string_append_c (str, '>');
493 else if (strcmp (buf, "amp") == 0)
494 g_string_append_c (str, '&');
495 else if (strcmp (buf, "quot") == 0)
496 g_string_append_c (str, '"');
497 else if (strcmp (buf, "apos") == 0)
498 g_string_append_c (str, '\'');
501 set_unescape_error (context, error,
503 G_MARKUP_ERROR_PARSE,
504 _("Entity name '%s' is not known"),
510 set_unescape_error (context, error,
511 /* give line number of the & */
513 G_MARKUP_ERROR_PARSE,
514 _("Entity did not end with a semicolon; "
515 "most likely you used an ampersand "
516 "character without intending to start "
517 "an entity - escape ampersand as &"));
523 case USTATE_AFTER_CHARREF_HASH:
525 gboolean is_hex = FALSE;
529 p = g_utf8_next_char (p);
533 while (p != text_end && *p != ';')
534 p = g_utf8_next_char (p);
538 g_assert (*p == ';');
540 /* digit is between start and p */
544 gchar *digit = g_strndup (start, p - start);
547 gchar *digit_end = digit + (p - start);
551 l = strtoul (digit, &end, 16);
553 l = strtoul (digit, &end, 10);
555 if (end != digit_end || errno != 0)
557 set_unescape_error (context, error,
559 G_MARKUP_ERROR_PARSE,
560 _("Failed to parse '%s', which "
561 "should have been a digit "
562 "inside a character reference "
563 "(ê for example) - perhaps "
564 "the digit is too large"),
569 /* characters XML permits */
573 (l >= 0x20 && l <= 0xD7FF) ||
574 (l >= 0xE000 && l <= 0xFFFD) ||
575 (l >= 0x10000 && l <= 0x10FFFF))
578 g_string_append (str, char_str (l, buf));
582 set_unescape_error (context, error,
584 G_MARKUP_ERROR_PARSE,
585 _("Character reference '%s' does not encode a permitted character"),
592 /* Move to next state */
593 p = g_utf8_next_char (p); /* past semicolon */
595 state = USTATE_INSIDE_TEXT;
599 set_unescape_error (context, error,
601 G_MARKUP_ERROR_PARSE,
602 _("Empty character reference; "
603 "should include a digit such as "
609 set_unescape_error (context, error,
611 G_MARKUP_ERROR_PARSE,
612 _("Character reference did not end with a "
614 "most likely you used an ampersand "
615 "character without intending to start "
616 "an entity - escape ampersand as &"));
622 g_assert_not_reached ();
627 if (context->state != STATE_ERROR)
631 case USTATE_INSIDE_TEXT:
633 case USTATE_AFTER_AMPERSAND:
634 case USTATE_INSIDE_ENTITY_NAME:
635 set_unescape_error (context, error,
637 G_MARKUP_ERROR_PARSE,
638 _("Unfinished entity reference"));
640 case USTATE_AFTER_CHARREF_HASH:
641 set_unescape_error (context, error,
643 G_MARKUP_ERROR_PARSE,
644 _("Unfinished character reference"));
649 if (context->state == STATE_ERROR)
651 g_string_free (str, TRUE);
657 *unescaped = g_string_free (str, FALSE);
665 advance_char (GMarkupParseContext *context)
667 g_return_val_if_fail (context->iter != context->current_text_end, FALSE);
669 context->iter = g_utf8_next_char (context->iter);
670 context->char_number += 1;
672 if (context->iter == context->current_text_end)
675 if (*context->iter == '\n')
677 context->line_number += 1;
678 context->char_number = 1;
687 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
691 skip_spaces (GMarkupParseContext *context)
695 if (!xml_isspace (*context->iter))
698 while (advance_char (context));
702 advance_to_name_end (GMarkupParseContext *context)
706 if (!is_name_char (g_utf8_get_char (context->iter)))
709 while (advance_char (context));
713 add_to_partial (GMarkupParseContext *context,
714 const gchar *text_start,
715 const gchar *text_end)
717 if (context->partial_chunk == NULL)
718 context->partial_chunk = g_string_new (NULL);
720 if (text_start != text_end)
721 g_string_append_len (context->partial_chunk, text_start,
722 text_end - text_start);
724 /* Invariant here that partial_chunk exists */
728 truncate_partial (GMarkupParseContext *context)
730 if (context->partial_chunk != NULL)
732 context->partial_chunk = g_string_truncate (context->partial_chunk, 0);
737 current_element (GMarkupParseContext *context)
739 return context->tag_stack->data;
743 current_attribute (GMarkupParseContext *context)
745 g_assert (context->cur_attr >= 0);
746 return context->attr_names[context->cur_attr];
750 find_current_text_end (GMarkupParseContext *context)
752 /* This function must be safe (non-segfaulting) on invalid UTF8 */
753 const gchar *end = context->current_text + context->current_text_len;
757 g_assert (context->current_text_len > 0);
759 p = context->current_text;
760 next = g_utf8_find_next_char (p, end);
762 while (next && *next)
767 next = g_utf8_find_next_char (p, end);
770 /* p is now the start of the last character or character portion. */
772 next = g_utf8_next_char (p); /* this only touches *p, nothing beyond */
776 /* whole character */
777 context->current_text_end = end;
782 context->leftover_char_portion = g_string_new_len (p, end - p);
783 context->current_text_len -= (end - p);
784 context->current_text_end = p;
790 add_attribute (GMarkupParseContext *context, char *name)
792 if (context->cur_attr + 2 >= context->alloc_attrs)
794 context->alloc_attrs += 5; /* silly magic number */
795 context->attr_names = g_realloc (context->attr_names, sizeof(char*)*context->alloc_attrs);
796 context->attr_values = g_realloc (context->attr_values, sizeof(char*)*context->alloc_attrs);
799 context->attr_names[context->cur_attr] = name;
800 context->attr_values[context->cur_attr] = NULL;
801 context->attr_names[context->cur_attr+1] = NULL;
802 context->attr_values[context->cur_attr+1] = NULL;
806 * g_markup_parse_context_parse:
807 * @context: a #GMarkupParseContext
808 * @text: chunk of text to parse
809 * @text_len: length of @text in bytes
810 * @error: return location for a #GError
812 * Feed some data to the #GMarkupParseContext. The data need not
813 * be valid UTF-8; an error will be signaled if it's invalid.
814 * The data need not be an entire document; you can feed a document
815 * into the parser incrementally, via multiple calls to this function.
816 * Typically, as you receive data from a network connection or file,
817 * you feed each received chunk of data into this function, aborting
818 * the process if an error occurs. Once an error is reported, no further
819 * data may be fed to the #GMarkupParseContext; all errors are fatal.
821 * Return value: %FALSE if an error occurred, %TRUE on success
824 g_markup_parse_context_parse (GMarkupParseContext *context,
829 const gchar *first_invalid;
831 g_return_val_if_fail (context != NULL, FALSE);
832 g_return_val_if_fail (text != NULL, FALSE);
833 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
834 g_return_val_if_fail (!context->parsing, FALSE);
837 text_len = strlen (text);
842 context->parsing = TRUE;
844 if (context->leftover_char_portion)
846 const gchar *first_char;
848 if ((*text & 0xc0) != 0x80)
851 first_char = g_utf8_find_next_char (text, text + text_len);
855 /* leftover_char_portion was completed. Parse it. */
856 GString *portion = context->leftover_char_portion;
858 g_string_append_len (context->leftover_char_portion,
859 text, first_char - text);
861 /* hacks to allow recursion */
862 context->parsing = FALSE;
863 context->leftover_char_portion = NULL;
865 if (!g_markup_parse_context_parse (context,
866 portion->str, portion->len,
869 g_assert (context->state == STATE_ERROR);
872 g_string_free (portion, TRUE);
873 context->parsing = TRUE;
875 /* Skip the fraction of char that was in this text */
876 text_len -= (first_char - text);
881 /* another little chunk of the leftover char; geez
882 * someone is inefficient.
884 g_string_append_len (context->leftover_char_portion,
887 if (context->leftover_char_portion->len > 7)
889 /* The leftover char portion is too big to be
894 G_MARKUP_ERROR_BAD_UTF8,
895 _("Invalid UTF-8 encoded text"));
902 context->current_text = text;
903 context->current_text_len = text_len;
904 context->iter = context->current_text;
905 context->start = context->iter;
907 /* Nothing left after finishing the leftover char, or nothing
908 * passed in to begin with.
910 if (context->current_text_len == 0)
913 /* find_current_text_end () assumes the string starts at
914 * a character start, so we need to validate at least
915 * that much. It doesn't assume any following bytes
918 if ((*context->current_text & 0xc0) == 0x80) /* not a char start */
922 G_MARKUP_ERROR_BAD_UTF8,
923 _("Invalid UTF-8 encoded text"));
927 /* Initialize context->current_text_end, possibly adjusting
928 * current_text_len, and add any leftover char portion
930 find_current_text_end (context);
932 /* Validate UTF8 (must be done after we find the end, since
933 * we could have a trailing incomplete char)
935 if (!g_utf8_validate (context->current_text,
936 context->current_text_len,
941 p = context->current_text;
942 while (p != context->current_text_end)
949 context->line_number += newlines;
953 G_MARKUP_ERROR_BAD_UTF8,
954 _("Invalid UTF-8 encoded text"));
958 while (context->iter != context->current_text_end)
960 switch (context->state)
963 /* Possible next state: AFTER_OPEN_ANGLE */
965 g_assert (context->tag_stack == NULL);
967 /* whitespace is ignored outside of any elements */
968 skip_spaces (context);
970 if (context->iter != context->current_text_end)
972 if (*context->iter == '<')
974 /* Move after the open angle */
975 advance_char (context);
977 context->state = STATE_AFTER_OPEN_ANGLE;
979 /* this could start a passthrough */
980 context->start = context->iter;
982 /* document is now non-empty */
983 context->document_empty = FALSE;
989 G_MARKUP_ERROR_PARSE,
990 _("Document must begin with an element (e.g. <book>)"));
995 case STATE_AFTER_OPEN_ANGLE:
996 /* Possible next states: INSIDE_OPEN_TAG_NAME,
997 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
999 if (*context->iter == '?' ||
1000 *context->iter == '!')
1002 /* include < in the passthrough */
1003 const gchar *openangle = "<";
1004 add_to_partial (context, openangle, openangle + 1);
1005 context->start = context->iter;
1006 context->balance = 1;
1007 context->state = STATE_INSIDE_PASSTHROUGH;
1009 else if (*context->iter == '/')
1012 advance_char (context);
1014 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1016 else if (is_name_start_char (g_utf8_get_char (context->iter)))
1018 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1020 /* start of tag name */
1021 context->start = context->iter;
1028 G_MARKUP_ERROR_PARSE,
1029 _("'%s' is not a valid character following "
1030 "a '<' character; it may not begin an "
1032 utf8_str (context->iter, buf));
1036 /* The AFTER_CLOSE_ANGLE state is actually sort of
1037 * broken, because it doesn't correspond to a range
1038 * of characters in the input stream as the others do,
1039 * and thus makes things harder to conceptualize
1041 case STATE_AFTER_CLOSE_ANGLE:
1042 /* Possible next states: INSIDE_TEXT, STATE_START */
1043 if (context->tag_stack == NULL)
1045 context->start = NULL;
1046 context->state = STATE_START;
1050 context->start = context->iter;
1051 context->state = STATE_INSIDE_TEXT;
1055 case STATE_AFTER_ELISION_SLASH:
1056 /* Possible next state: AFTER_CLOSE_ANGLE */
1059 /* We need to pop the tag stack and call the end_element
1060 * function, since this is the close tag
1062 GError *tmp_error = NULL;
1064 g_assert (context->tag_stack != NULL);
1067 if (context->parser->end_element)
1068 (* context->parser->end_element) (context,
1069 context->tag_stack->data,
1075 mark_error (context, tmp_error);
1076 g_propagate_error (error, tmp_error);
1080 if (*context->iter == '>')
1082 /* move after the close angle */
1083 advance_char (context);
1084 context->state = STATE_AFTER_CLOSE_ANGLE;
1091 G_MARKUP_ERROR_PARSE,
1092 _("Odd character '%s', expected a '>' character "
1093 "to end the start tag of element '%s'"),
1094 utf8_str (context->iter, buf),
1095 current_element (context));
1099 g_free (context->tag_stack->data);
1100 context->tag_stack = g_slist_delete_link (context->tag_stack,
1101 context->tag_stack);
1105 case STATE_INSIDE_OPEN_TAG_NAME:
1106 /* Possible next states: BETWEEN_ATTRIBUTES */
1108 /* if there's a partial chunk then it's the first part of the
1109 * tag name. If there's a context->start then it's the start
1110 * of the tag name in current_text, the partial chunk goes
1111 * before that start though.
1113 advance_to_name_end (context);
1115 if (context->iter == context->current_text_end)
1117 /* The name hasn't necessarily ended. Merge with
1118 * partial chunk, leave state unchanged.
1120 add_to_partial (context, context->start, context->iter);
1124 /* The name has ended. Combine it with the partial chunk
1125 * if any; push it on the stack; enter next state.
1127 add_to_partial (context, context->start, context->iter);
1128 context->tag_stack =
1129 g_slist_prepend (context->tag_stack,
1130 g_string_free (context->partial_chunk,
1133 context->partial_chunk = NULL;
1135 context->state = STATE_BETWEEN_ATTRIBUTES;
1136 context->start = NULL;
1140 case STATE_INSIDE_ATTRIBUTE_NAME:
1141 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1143 advance_to_name_end (context);
1144 add_to_partial (context, context->start, context->iter);
1146 /* read the full name, if we enter the equals sign state
1147 * then add the attribute to the list (without the value),
1148 * otherwise store a partial chunk to be prepended later.
1150 if (context->iter != context->current_text_end)
1151 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1154 case STATE_AFTER_ATTRIBUTE_NAME:
1155 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1157 skip_spaces (context);
1159 if (context->iter != context->current_text_end)
1161 /* The name has ended. Combine it with the partial chunk
1162 * if any; push it on the stack; enter next state.
1164 add_attribute (context, g_string_free (context->partial_chunk, FALSE));
1166 context->partial_chunk = NULL;
1167 context->start = NULL;
1169 if (*context->iter == '=')
1171 advance_char (context);
1172 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1179 G_MARKUP_ERROR_PARSE,
1180 _("Odd character '%s', expected a '=' after "
1181 "attribute name '%s' of element '%s'"),
1182 utf8_str (context->iter, buf),
1183 current_attribute (context),
1184 current_element (context));
1190 case STATE_BETWEEN_ATTRIBUTES:
1191 /* Possible next states: AFTER_CLOSE_ANGLE,
1192 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1194 skip_spaces (context);
1196 if (context->iter != context->current_text_end)
1198 if (*context->iter == '/')
1200 advance_char (context);
1201 context->state = STATE_AFTER_ELISION_SLASH;
1203 else if (*context->iter == '>')
1206 advance_char (context);
1207 context->state = STATE_AFTER_CLOSE_ANGLE;
1209 else if (is_name_start_char (g_utf8_get_char (context->iter)))
1211 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1212 /* start of attribute name */
1213 context->start = context->iter;
1220 G_MARKUP_ERROR_PARSE,
1221 _("Odd character '%s', expected a '>' or '/' "
1222 "character to end the start tag of "
1223 "element '%s', or optionally an attribute; "
1224 "perhaps you used an invalid character in "
1225 "an attribute name"),
1226 utf8_str (context->iter, buf),
1227 current_element (context));
1230 /* If we're done with attributes, invoke
1231 * the start_element callback
1233 if (context->state == STATE_AFTER_ELISION_SLASH ||
1234 context->state == STATE_AFTER_CLOSE_ANGLE)
1236 const gchar *start_name;
1237 /* Ugly, but the current code expects an empty array instead of NULL */
1238 const gchar *empty = NULL;
1239 const gchar **attr_names = ∅
1240 const gchar **attr_values = ∅
1243 /* Call user callback for element start */
1244 start_name = current_element (context);
1246 if (context->cur_attr >= 0)
1248 attr_names = (const gchar**)context->attr_names;
1249 attr_values = (const gchar**)context->attr_values;
1253 if (context->parser->start_element)
1254 (* context->parser->start_element) (context,
1256 (const gchar **)attr_names,
1257 (const gchar **)attr_values,
1261 /* Go ahead and free the attributes. */
1262 for (; context->cur_attr >= 0; context->cur_attr--)
1264 int pos = context->cur_attr;
1265 g_free (context->attr_names[pos]);
1266 g_free (context->attr_values[pos]);
1267 context->attr_names[pos] = context->attr_values[pos] = NULL;
1269 g_assert (context->cur_attr == -1);
1270 g_assert (context->attr_names == NULL ||
1271 context->attr_names[0] == NULL);
1272 g_assert (context->attr_values == NULL ||
1273 context->attr_values[0] == NULL);
1275 if (tmp_error != NULL)
1277 mark_error (context, tmp_error);
1278 g_propagate_error (error, tmp_error);
1284 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1285 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1287 skip_spaces (context);
1289 if (context->iter != context->current_text_end)
1291 if (*context->iter == '"')
1293 advance_char (context);
1294 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1295 context->start = context->iter;
1297 else if (*context->iter == '\'')
1299 advance_char (context);
1300 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1301 context->start = context->iter;
1308 G_MARKUP_ERROR_PARSE,
1309 _("Odd character '%s', expected an open quote mark "
1310 "after the equals sign when giving value for "
1311 "attribute '%s' of element '%s'"),
1312 utf8_str (context->iter, buf),
1313 current_attribute (context),
1314 current_element (context));
1319 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1320 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1321 /* Possible next states: BETWEEN_ATTRIBUTES */
1325 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1336 if (*context->iter == delim)
1339 while (advance_char (context));
1341 if (context->iter == context->current_text_end)
1343 /* The value hasn't necessarily ended. Merge with
1344 * partial chunk, leave state unchanged.
1346 add_to_partial (context, context->start, context->iter);
1350 /* The value has ended at the quote mark. Combine it
1351 * with the partial chunk if any; set it for the current
1354 add_to_partial (context, context->start, context->iter);
1356 g_assert (context->cur_attr >= 0);
1358 if (unescape_text (context,
1359 context->partial_chunk->str,
1360 context->partial_chunk->str +
1361 context->partial_chunk->len,
1362 &context->attr_values[context->cur_attr],
1365 /* success, advance past quote and set state. */
1366 advance_char (context);
1367 context->state = STATE_BETWEEN_ATTRIBUTES;
1368 context->start = NULL;
1371 truncate_partial (context);
1375 case STATE_INSIDE_TEXT:
1376 /* Possible next states: AFTER_OPEN_ANGLE */
1379 if (*context->iter == '<')
1382 while (advance_char (context));
1384 /* The text hasn't necessarily ended. Merge with
1385 * partial chunk, leave state unchanged.
1388 add_to_partial (context, context->start, context->iter);
1390 if (context->iter != context->current_text_end)
1392 gchar *unescaped = NULL;
1394 /* The text has ended at the open angle. Call the text
1398 if (unescape_text (context,
1399 context->partial_chunk->str,
1400 context->partial_chunk->str +
1401 context->partial_chunk->len,
1405 GError *tmp_error = NULL;
1407 if (context->parser->text)
1408 (*context->parser->text) (context,
1416 if (tmp_error == NULL)
1418 /* advance past open angle and set state. */
1419 advance_char (context);
1420 context->state = STATE_AFTER_OPEN_ANGLE;
1421 /* could begin a passthrough */
1422 context->start = context->iter;
1426 mark_error (context, tmp_error);
1427 g_propagate_error (error, tmp_error);
1431 truncate_partial (context);
1435 case STATE_AFTER_CLOSE_TAG_SLASH:
1436 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1437 if (is_name_start_char (g_utf8_get_char (context->iter)))
1439 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1441 /* start of tag name */
1442 context->start = context->iter;
1449 G_MARKUP_ERROR_PARSE,
1450 _("'%s' is not a valid character following "
1451 "the characters '</'; '%s' may not begin an "
1453 utf8_str (context->iter, buf),
1454 utf8_str (context->iter, buf));
1458 case STATE_INSIDE_CLOSE_TAG_NAME:
1459 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1460 advance_to_name_end (context);
1461 add_to_partial (context, context->start, context->iter);
1463 if (context->iter != context->current_text_end)
1464 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1467 case STATE_AFTER_CLOSE_TAG_NAME:
1468 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1470 skip_spaces (context);
1472 if (context->iter != context->current_text_end)
1476 /* The name has ended. Combine it with the partial chunk
1477 * if any; check that it matches stack top and pop
1478 * stack; invoke proper callback; enter next state.
1480 close_name = g_string_free (context->partial_chunk, FALSE);
1481 context->partial_chunk = NULL;
1483 if (*context->iter != '>')
1488 G_MARKUP_ERROR_PARSE,
1489 _("'%s' is not a valid character following "
1490 "the close element name '%s'; the allowed "
1491 "character is '>'"),
1492 utf8_str (context->iter, buf),
1495 else if (context->tag_stack == NULL)
1499 G_MARKUP_ERROR_PARSE,
1500 _("Element '%s' was closed, no element "
1501 "is currently open"),
1504 else if (strcmp (close_name, current_element (context)) != 0)
1508 G_MARKUP_ERROR_PARSE,
1509 _("Element '%s' was closed, but the currently "
1510 "open element is '%s'"),
1512 current_element (context));
1517 advance_char (context);
1518 context->state = STATE_AFTER_CLOSE_ANGLE;
1519 context->start = NULL;
1521 /* call the end_element callback */
1523 if (context->parser->end_element)
1524 (* context->parser->end_element) (context,
1530 /* Pop the tag stack */
1531 g_free (context->tag_stack->data);
1532 context->tag_stack = g_slist_delete_link (context->tag_stack,
1533 context->tag_stack);
1537 mark_error (context, tmp_error);
1538 g_propagate_error (error, tmp_error);
1542 g_free (close_name);
1546 case STATE_INSIDE_PASSTHROUGH:
1547 /* Possible next state: AFTER_CLOSE_ANGLE */
1550 if (*context->iter == '<')
1552 if (*context->iter == '>')
1555 add_to_partial (context, context->start, context->iter);
1556 context->start = context->iter;
1557 if ((g_str_has_prefix (context->partial_chunk->str, "<?")
1558 && g_str_has_suffix (context->partial_chunk->str, "?")) ||
1559 (g_str_has_prefix (context->partial_chunk->str, "<!--")
1560 && g_str_has_suffix (context->partial_chunk->str, "--")) ||
1561 (g_str_has_prefix (context->partial_chunk->str, "<![CDATA[")
1562 && g_str_has_suffix (context->partial_chunk->str, "]]")) ||
1563 (g_str_has_prefix (context->partial_chunk->str, "<!DOCTYPE")
1564 && context->balance == 0))
1568 while (advance_char (context));
1570 if (context->iter == context->current_text_end)
1572 /* The passthrough hasn't necessarily ended. Merge with
1573 * partial chunk, leave state unchanged.
1575 add_to_partial (context, context->start, context->iter);
1579 /* The passthrough has ended at the close angle. Combine
1580 * it with the partial chunk if any. Call the passthrough
1581 * callback. Note that the open/close angles are
1582 * included in the text of the passthrough.
1584 GError *tmp_error = NULL;
1586 advance_char (context); /* advance past close angle */
1587 add_to_partial (context, context->start, context->iter);
1589 if (context->parser->passthrough)
1590 (*context->parser->passthrough) (context,
1591 context->partial_chunk->str,
1592 context->partial_chunk->len,
1596 truncate_partial (context);
1598 if (tmp_error == NULL)
1600 context->state = STATE_AFTER_CLOSE_ANGLE;
1601 context->start = context->iter; /* could begin text */
1605 mark_error (context, tmp_error);
1606 g_propagate_error (error, tmp_error);
1616 g_assert_not_reached ();
1622 context->parsing = FALSE;
1624 return context->state != STATE_ERROR;
1628 * g_markup_parse_context_end_parse:
1629 * @context: a #GMarkupParseContext
1630 * @error: return location for a #GError
1632 * Signals to the #GMarkupParseContext that all data has been
1633 * fed into the parse context with g_markup_parse_context_parse().
1634 * This function reports an error if the document isn't complete,
1635 * for example if elements are still open.
1637 * Return value: %TRUE on success, %FALSE if an error was set
1640 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1643 g_return_val_if_fail (context != NULL, FALSE);
1644 g_return_val_if_fail (!context->parsing, FALSE);
1645 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1647 if (context->partial_chunk != NULL)
1649 g_string_free (context->partial_chunk, TRUE);
1650 context->partial_chunk = NULL;
1653 if (context->document_empty)
1655 set_error (context, error, G_MARKUP_ERROR_EMPTY,
1656 _("Document was empty or contained only whitespace"));
1660 context->parsing = TRUE;
1662 switch (context->state)
1668 case STATE_AFTER_OPEN_ANGLE:
1669 set_error (context, error, G_MARKUP_ERROR_PARSE,
1670 _("Document ended unexpectedly just after an open angle bracket '<'"));
1673 case STATE_AFTER_CLOSE_ANGLE:
1674 if (context->tag_stack != NULL)
1676 /* Error message the same as for INSIDE_TEXT */
1677 set_error (context, error, G_MARKUP_ERROR_PARSE,
1678 _("Document ended unexpectedly with elements still open - "
1679 "'%s' was the last element opened"),
1680 current_element (context));
1684 case STATE_AFTER_ELISION_SLASH:
1685 set_error (context, error, G_MARKUP_ERROR_PARSE,
1686 _("Document ended unexpectedly, expected to see a close angle "
1687 "bracket ending the tag <%s/>"), current_element (context));
1690 case STATE_INSIDE_OPEN_TAG_NAME:
1691 set_error (context, error, G_MARKUP_ERROR_PARSE,
1692 _("Document ended unexpectedly inside an element name"));
1695 case STATE_INSIDE_ATTRIBUTE_NAME:
1696 set_error (context, error, G_MARKUP_ERROR_PARSE,
1697 _("Document ended unexpectedly inside an attribute name"));
1700 case STATE_BETWEEN_ATTRIBUTES:
1701 set_error (context, error, G_MARKUP_ERROR_PARSE,
1702 _("Document ended unexpectedly inside an element-opening "
1706 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1707 set_error (context, error, G_MARKUP_ERROR_PARSE,
1708 _("Document ended unexpectedly after the equals sign "
1709 "following an attribute name; no attribute value"));
1712 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1713 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1714 set_error (context, error, G_MARKUP_ERROR_PARSE,
1715 _("Document ended unexpectedly while inside an attribute "
1719 case STATE_INSIDE_TEXT:
1720 g_assert (context->tag_stack != NULL);
1721 set_error (context, error, G_MARKUP_ERROR_PARSE,
1722 _("Document ended unexpectedly with elements still open - "
1723 "'%s' was the last element opened"),
1724 current_element (context));
1727 case STATE_AFTER_CLOSE_TAG_SLASH:
1728 case STATE_INSIDE_CLOSE_TAG_NAME:
1729 set_error (context, error, G_MARKUP_ERROR_PARSE,
1730 _("Document ended unexpectedly inside the close tag for "
1731 "element '%s'"), current_element);
1734 case STATE_INSIDE_PASSTHROUGH:
1735 set_error (context, error, G_MARKUP_ERROR_PARSE,
1736 _("Document ended unexpectedly inside a comment or "
1737 "processing instruction"));
1742 g_assert_not_reached ();
1746 context->parsing = FALSE;
1748 return context->state != STATE_ERROR;
1752 * g_markup_parse_context_get_element:
1753 * @context: a #GMarkupParseContext
1754 * @returns: the name of the currently open element, or %NULL
1756 * Retrieves the name of the currently open element.
1760 G_CONST_RETURN gchar *
1761 g_markup_parse_context_get_element (GMarkupParseContext *context)
1763 g_return_val_if_fail (context != NULL, NULL);
1765 if (context->tag_stack == NULL)
1768 return current_element (context);
1772 * g_markup_parse_context_get_position:
1773 * @context: a #GMarkupParseContext
1774 * @line_number: return location for a line number, or %NULL
1775 * @char_number: return location for a char-on-line number, or %NULL
1777 * Retrieves the current line number and the number of the character on
1778 * that line. Intended for use in error messages; there are no strict
1779 * semantics for what constitutes the "current" line number other than
1780 * "the best number we could come up with for error messages."
1784 g_markup_parse_context_get_position (GMarkupParseContext *context,
1788 g_return_if_fail (context != NULL);
1791 *line_number = context->line_number;
1794 *char_number = context->char_number;
1798 append_escaped_text (GString *str,
1806 end = text + length;
1811 next = g_utf8_next_char (p);
1816 g_string_append (str, "&");
1820 g_string_append (str, "<");
1824 g_string_append (str, ">");
1828 g_string_append (str, "'");
1832 g_string_append (str, """);
1836 g_string_append_len (str, p, next - p);
1845 * g_markup_escape_text:
1846 * @text: some valid UTF-8 text
1847 * @length: length of @text in bytes
1849 * Escapes text so that the markup parser will parse it verbatim.
1850 * Less than, greater than, ampersand, etc. are replaced with the
1851 * corresponding entities. This function would typically be used
1852 * when writing out a file to be parsed with the markup parser.
1854 * Note that this function doesn't protect whitespace and line endings
1855 * from being processed according to the XML rules for normalization
1856 * of line endings and attribute values.
1858 * Return value: escaped text
1861 g_markup_escape_text (const gchar *text,
1866 g_return_val_if_fail (text != NULL, NULL);
1869 length = strlen (text);
1871 str = g_string_new (NULL);
1872 append_escaped_text (str, text, length);
1874 return g_string_free (str, FALSE);
1879 * @format: a printf-style format string
1880 * @after: location to store a pointer to the character after
1881 * the returned conversion. On a %NULL return, returns the
1882 * pointer to the trailing NUL in the string
1884 * Find the next conversion in a printf-style format string.
1885 * Partially based on code from printf-parser.c,
1886 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
1888 * Return value: pointer to the next conversion in @format,
1889 * or %NULL, if none.
1892 find_conversion (const char *format,
1895 const char *start = format;
1898 while (*start != '\0' && *start != '%')
1915 /* Test for positional argument. */
1916 if (*cp >= '0' && *cp <= '9')
1920 for (np = cp; *np >= '0' && *np <= '9'; np++)
1926 /* Skip the flags. */
1940 /* Skip the field width. */
1945 /* Test for positional argument. */
1946 if (*cp >= '0' && *cp <= '9')
1950 for (np = cp; *np >= '0' && *np <= '9'; np++)
1958 for (; *cp >= '0' && *cp <= '9'; cp++)
1962 /* Skip the precision. */
1968 /* Test for positional argument. */
1969 if (*cp >= '0' && *cp <= '9')
1973 for (np = cp; *np >= '0' && *np <= '9'; np++)
1981 for (; *cp >= '0' && *cp <= '9'; cp++)
1986 /* Skip argument type/size specifiers. */
1987 while (*cp == 'h' ||
1996 /* Skip the conversion character. */
2004 * g_markup_vprintf_escaped:
2005 * @format: printf() style format string
2006 * @args: variable argument list, similar to vprintf()
2008 * Formats the data in @args according to @format, escaping
2009 * all string and character arguments in the fashion
2010 * of g_markup_escape_text(). See g_markup_printf_escaped().
2012 * Return value: newly allocated result from formatting
2013 * operation. Free with g_free().
2018 g_markup_vprintf_escaped (const char *format,
2023 GString *result = NULL;
2024 gchar *output1 = NULL;
2025 gchar *output2 = NULL;
2026 const char *p, *op1, *op2;
2029 /* The technique here, is that we make two format strings that
2030 * have the identical conversions in the identical order to the
2031 * original strings, but differ in the text in-between. We
2032 * then use the normal g_strdup_vprintf() to format the arguments
2033 * with the two new format strings. By comparing the results,
2034 * we can figure out what segments of the output come from
2035 * the the original format string, and what from the arguments,
2036 * and thus know what portions of the string to escape.
2038 * For instance, for:
2040 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2042 * We form the two format strings "%sX%dX" and %sY%sY". The results
2043 * of formatting with those two strings are
2045 * "%sX%dX" => "Susan & FredX5X"
2046 * "%sY%dY" => "Susan & FredY5Y"
2048 * To find the span of the first argument, we find the first position
2049 * where the two arguments differ, which tells us that the first
2050 * argument formatted to "Susan & Fred". We then escape that
2051 * to "Susan & Fred" and join up with the intermediate portions
2052 * of the format string and the second argument to get
2053 * "Susan & Fred ate 5 apples".
2056 /* Create the two modified format strings
2058 format1 = g_string_new (NULL);
2059 format2 = g_string_new (NULL);
2064 const char *conv = find_conversion (p, &after);
2068 g_string_append_len (format1, conv, after - conv);
2069 g_string_append_c (format1, 'X');
2070 g_string_append_len (format2, conv, after - conv);
2071 g_string_append_c (format2, 'Y');
2076 /* Use them to format the arguments
2078 G_VA_COPY (args2, args);
2080 output1 = g_strdup_vprintf (format1->str, args);
2085 output2 = g_strdup_vprintf (format2->str, args2);
2090 result = g_string_new (NULL);
2092 /* Iterate through the original format string again,
2093 * copying the non-conversion portions and the escaped
2094 * converted arguments to the output string.
2102 const char *output_start;
2103 const char *conv = find_conversion (p, &after);
2106 if (!conv) /* The end, after points to the trailing \0 */
2108 g_string_append_len (result, p, after - p);
2112 g_string_append_len (result, p, conv - p);
2114 while (*op1 == *op2)
2120 escaped = g_markup_escape_text (output_start, op1 - output_start);
2121 g_string_append (result, escaped);
2130 g_string_free (format1, TRUE);
2131 g_string_free (format2, TRUE);
2136 return g_string_free (result, FALSE);
2142 * g_markup_printf_escaped:
2143 * @format: printf() style format string
2144 * @Varargs: the arguments to insert in the format string
2146 * Formats arguments according to @format, escaping
2147 * all string and character arguments in the fashion
2148 * of g_markup_escape_text(). This is useful when you
2149 * want to insert literal strings into XML-style markup
2150 * output, without having to worry that the strings
2151 * might themselves contain markup.
2153 * <informalexample><programlisting>
2154 * const char *store = "Fortnum & Mason";
2155 * const char *item = "Tea";
2158 * output = g_markup_printf_escaped ("<purchase>"
2159 * "<store>%s</store>"
2160 * "<item>%s</item>"
2161 * "</purchase>",
2163 * </programlisting></informalexample>
2165 * Return value: newly allocated result from formatting
2166 * operation. Free with g_free().
2171 g_markup_printf_escaped (const char *format, ...)
2176 va_start (args, format);
2177 result = g_markup_vprintf_escaped (format, args);