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.
35 g_markup_error_quark (void)
37 static GQuark error_quark = 0;
40 error_quark = g_quark_from_static_string ("g-markup-error-quark");
48 STATE_AFTER_OPEN_ANGLE,
49 STATE_AFTER_CLOSE_ANGLE,
50 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
51 STATE_INSIDE_OPEN_TAG_NAME,
52 STATE_INSIDE_ATTRIBUTE_NAME,
53 STATE_AFTER_ATTRIBUTE_NAME,
54 STATE_BETWEEN_ATTRIBUTES,
55 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
56 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
57 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
59 STATE_AFTER_CLOSE_TAG_SLASH,
60 STATE_INSIDE_CLOSE_TAG_NAME,
61 STATE_AFTER_CLOSE_TAG_NAME,
62 STATE_INSIDE_PASSTHROUGH,
66 struct _GMarkupParseContext
68 const GMarkupParser *parser;
70 GMarkupParseFlags flags;
76 GDestroyNotify dnotify;
78 /* A piece of character data or an element that
79 * hasn't "ended" yet so we haven't yet called
80 * the callback for it.
82 GString *partial_chunk;
84 GMarkupParseState state;
91 const gchar *current_text;
92 gssize current_text_len;
93 const gchar *current_text_end;
95 GString *leftover_char_portion;
97 /* used to save the start of the last interesting thingy */
102 guint document_empty : 1;
108 * g_markup_parse_context_new:
109 * @parser: a #GMarkupParser
110 * @flags: one or more #GMarkupParseFlags
111 * @user_data: user data to pass to #GMarkupParser functions
112 * @user_data_dnotify: user data destroy notifier called when the parse context is freed
114 * Creates a new parse context. A parse context is used to parse
115 * marked-up documents. You can feed any number of documents into
116 * a context, as long as no errors occur; once an error occurs,
117 * the parse context can't continue to parse text (you have to free it
118 * and create a new parse context).
120 * Return value: a new #GMarkupParseContext
122 GMarkupParseContext *
123 g_markup_parse_context_new (const GMarkupParser *parser,
124 GMarkupParseFlags flags,
126 GDestroyNotify user_data_dnotify)
128 GMarkupParseContext *context;
130 g_return_val_if_fail (parser != NULL, NULL);
132 context = g_new (GMarkupParseContext, 1);
134 context->parser = parser;
135 context->flags = flags;
136 context->user_data = user_data;
137 context->dnotify = user_data_dnotify;
139 context->line_number = 1;
140 context->char_number = 1;
142 context->partial_chunk = NULL;
144 context->state = STATE_START;
145 context->tag_stack = NULL;
146 context->attr_names = NULL;
147 context->attr_values = NULL;
148 context->cur_attr = -1;
149 context->alloc_attrs = 0;
151 context->current_text = NULL;
152 context->current_text_len = -1;
153 context->current_text_end = NULL;
154 context->leftover_char_portion = NULL;
156 context->start = NULL;
157 context->iter = NULL;
159 context->document_empty = TRUE;
160 context->parsing = FALSE;
162 context->balance = 0;
168 * g_markup_parse_context_free:
169 * @context: a #GMarkupParseContext
171 * Frees a #GMarkupParseContext. Can't be called from inside
172 * one of the #GMarkupParser functions.
176 g_markup_parse_context_free (GMarkupParseContext *context)
178 g_return_if_fail (context != NULL);
179 g_return_if_fail (!context->parsing);
181 if (context->dnotify)
182 (* context->dnotify) (context->user_data);
184 g_strfreev (context->attr_names);
185 g_strfreev (context->attr_values);
187 g_slist_foreach (context->tag_stack, (GFunc)g_free, NULL);
188 g_slist_free (context->tag_stack);
190 if (context->partial_chunk)
191 g_string_free (context->partial_chunk, TRUE);
193 if (context->leftover_char_portion)
194 g_string_free (context->leftover_char_portion, TRUE);
200 mark_error (GMarkupParseContext *context,
203 context->state = STATE_ERROR;
205 if (context->parser->error)
206 (*context->parser->error) (context, error, context->user_data);
210 set_error (GMarkupParseContext *context,
220 va_start (args, format);
221 s = g_strdup_vprintf (format, args);
224 tmp_error = g_error_new (G_MARKUP_ERROR,
226 _("Error on line %d char %d: %s"),
227 context->line_number,
228 context->char_number,
233 mark_error (context, tmp_error);
235 g_propagate_error (error, tmp_error);
239 is_name_start_char (gunichar c)
241 if (g_unichar_isalpha (c) ||
250 is_name_char (gunichar c)
252 if (g_unichar_isalnum (c) ||
264 char_str (gunichar c,
268 g_unichar_to_utf8 (c, buf);
273 utf8_str (const gchar *utf8,
276 char_str (g_utf8_get_char (utf8), buf);
281 set_unescape_error (GMarkupParseContext *context,
283 const gchar *remaining_text,
284 const gchar *remaining_text_end,
292 gint remaining_newlines;
295 remaining_newlines = 0;
297 while (p != remaining_text_end)
300 ++remaining_newlines;
304 va_start (args, format);
305 s = g_strdup_vprintf (format, args);
308 tmp_error = g_error_new (G_MARKUP_ERROR,
310 _("Error on line %d: %s"),
311 context->line_number - remaining_newlines,
316 mark_error (context, tmp_error);
318 g_propagate_error (error, tmp_error);
324 USTATE_AFTER_AMPERSAND,
325 USTATE_INSIDE_ENTITY_NAME,
326 USTATE_AFTER_CHARREF_HASH
330 unescape_text (GMarkupParseContext *context,
332 const gchar *text_end,
336 #define MAX_ENT_LEN 5
341 gboolean normalize_attribute;
343 str = g_string_new (NULL);
345 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
346 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
347 normalize_attribute = TRUE;
349 normalize_attribute = FALSE;
351 state = USTATE_INSIDE_TEXT;
354 while (p != text_end && context->state != STATE_ERROR)
356 g_assert (p < text_end);
360 case USTATE_INSIDE_TEXT:
362 while (p != text_end && *p != '&')
364 if ((*p == '\t' || *p == '\n') && normalize_attribute)
366 g_string_append_len (str, start, p - start);
367 g_string_append_c (str, ' ');
368 p = g_utf8_next_char (p);
373 g_string_append_len (str, start, p - start);
374 g_string_append_c (str, normalize_attribute ? ' ' : '\n');
375 p = g_utf8_next_char (p);
377 p = g_utf8_next_char (p);
381 p = g_utf8_next_char (p);
386 g_string_append_len (str, start, p - start);
391 if (p != text_end && *p == '&')
393 p = g_utf8_next_char (p);
394 state = USTATE_AFTER_AMPERSAND;
399 case USTATE_AFTER_AMPERSAND:
403 p = g_utf8_next_char (p);
406 state = USTATE_AFTER_CHARREF_HASH;
408 else if (!is_name_start_char (g_utf8_get_char (p)))
412 set_unescape_error (context, error,
414 G_MARKUP_ERROR_PARSE,
415 _("Empty entity '&;' seen; valid "
416 "entities are: & " < > '"));
422 set_unescape_error (context, error,
424 G_MARKUP_ERROR_PARSE,
425 _("Character '%s' is not valid at "
426 "the start of an entity name; "
427 "the & character begins an entity; "
428 "if this ampersand isn't supposed "
429 "to be an entity, escape it as "
437 state = USTATE_INSIDE_ENTITY_NAME;
443 case USTATE_INSIDE_ENTITY_NAME:
445 gchar buf[MAX_ENT_LEN+1] = {
446 '\0', '\0', '\0', '\0', '\0', '\0'
450 while (p != text_end)
454 else if (!is_name_char (*p))
458 set_unescape_error (context, error,
460 G_MARKUP_ERROR_PARSE,
461 _("Character '%s' is not valid "
462 "inside an entity name"),
467 p = g_utf8_next_char (p);
470 if (context->state != STATE_ERROR)
485 /* move to after semicolon */
486 p = g_utf8_next_char (p);
488 state = USTATE_INSIDE_TEXT;
490 if (strcmp (buf, "lt") == 0)
491 g_string_append_c (str, '<');
492 else if (strcmp (buf, "gt") == 0)
493 g_string_append_c (str, '>');
494 else if (strcmp (buf, "amp") == 0)
495 g_string_append_c (str, '&');
496 else if (strcmp (buf, "quot") == 0)
497 g_string_append_c (str, '"');
498 else if (strcmp (buf, "apos") == 0)
499 g_string_append_c (str, '\'');
502 set_unescape_error (context, error,
504 G_MARKUP_ERROR_PARSE,
505 _("Entity name '%s' is not known"),
511 set_unescape_error (context, error,
512 /* give line number of the & */
514 G_MARKUP_ERROR_PARSE,
515 _("Entity did not end with a semicolon; "
516 "most likely you used an ampersand "
517 "character without intending to start "
518 "an entity - escape ampersand as &"));
524 case USTATE_AFTER_CHARREF_HASH:
526 gboolean is_hex = FALSE;
530 p = g_utf8_next_char (p);
534 while (p != text_end && *p != ';')
535 p = g_utf8_next_char (p);
539 g_assert (*p == ';');
541 /* digit is between start and p */
545 gchar *digit = g_strndup (start, p - start);
548 gchar *digit_end = digit + (p - start);
552 l = strtoul (digit, &end, 16);
554 l = strtoul (digit, &end, 10);
556 if (end != digit_end || errno != 0)
558 set_unescape_error (context, error,
560 G_MARKUP_ERROR_PARSE,
561 _("Failed to parse '%s', which "
562 "should have been a digit "
563 "inside a character reference "
564 "(ê for example) - perhaps "
565 "the digit is too large"),
570 /* characters XML permits */
574 (l >= 0x20 && l <= 0xD7FF) ||
575 (l >= 0xE000 && l <= 0xFFFD) ||
576 (l >= 0x10000 && l <= 0x10FFFF))
579 g_string_append (str, char_str (l, buf));
583 set_unescape_error (context, error,
585 G_MARKUP_ERROR_PARSE,
586 _("Character reference '%s' does not encode a permitted character"),
593 /* Move to next state */
594 p = g_utf8_next_char (p); /* past semicolon */
596 state = USTATE_INSIDE_TEXT;
600 set_unescape_error (context, error,
602 G_MARKUP_ERROR_PARSE,
603 _("Empty character reference; "
604 "should include a digit such as "
610 set_unescape_error (context, error,
612 G_MARKUP_ERROR_PARSE,
613 _("Character reference did not end with a "
615 "most likely you used an ampersand "
616 "character without intending to start "
617 "an entity - escape ampersand as &"));
623 g_assert_not_reached ();
628 if (context->state != STATE_ERROR)
632 case USTATE_INSIDE_TEXT:
634 case USTATE_AFTER_AMPERSAND:
635 case USTATE_INSIDE_ENTITY_NAME:
636 set_unescape_error (context, error,
638 G_MARKUP_ERROR_PARSE,
639 _("Unfinished entity reference"));
641 case USTATE_AFTER_CHARREF_HASH:
642 set_unescape_error (context, error,
644 G_MARKUP_ERROR_PARSE,
645 _("Unfinished character reference"));
650 if (context->state == STATE_ERROR)
652 g_string_free (str, TRUE);
658 *unescaped = g_string_free (str, FALSE);
666 advance_char (GMarkupParseContext *context)
668 g_return_val_if_fail (context->iter != context->current_text_end, FALSE);
670 context->iter = g_utf8_next_char (context->iter);
671 context->char_number += 1;
673 if (context->iter == context->current_text_end)
676 if (*context->iter == '\n')
678 context->line_number += 1;
679 context->char_number = 1;
688 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
692 skip_spaces (GMarkupParseContext *context)
696 if (!xml_isspace (*context->iter))
699 while (advance_char (context));
703 advance_to_name_end (GMarkupParseContext *context)
707 if (!is_name_char (g_utf8_get_char (context->iter)))
710 while (advance_char (context));
714 add_to_partial (GMarkupParseContext *context,
715 const gchar *text_start,
716 const gchar *text_end)
718 if (context->partial_chunk == NULL)
719 context->partial_chunk = g_string_new (NULL);
721 if (text_start != text_end)
722 g_string_append_len (context->partial_chunk, text_start,
723 text_end - text_start);
725 /* Invariant here that partial_chunk exists */
729 truncate_partial (GMarkupParseContext *context)
731 if (context->partial_chunk != NULL)
733 context->partial_chunk = g_string_truncate (context->partial_chunk, 0);
738 current_element (GMarkupParseContext *context)
740 return context->tag_stack->data;
744 current_attribute (GMarkupParseContext *context)
746 g_assert (context->cur_attr >= 0);
747 return context->attr_names[context->cur_attr];
751 find_current_text_end (GMarkupParseContext *context)
753 /* This function must be safe (non-segfaulting) on invalid UTF8 */
754 const gchar *end = context->current_text + context->current_text_len;
758 g_assert (context->current_text_len > 0);
760 p = context->current_text;
761 next = g_utf8_find_next_char (p, end);
763 while (next && *next)
768 next = g_utf8_find_next_char (p, end);
771 /* p is now the start of the last character or character portion. */
773 next = g_utf8_next_char (p); /* this only touches *p, nothing beyond */
777 /* whole character */
778 context->current_text_end = end;
783 context->leftover_char_portion = g_string_new_len (p, end - p);
784 context->current_text_len -= (end - p);
785 context->current_text_end = p;
791 add_attribute (GMarkupParseContext *context, char *name)
793 if (context->cur_attr + 2 >= context->alloc_attrs)
795 context->alloc_attrs += 5; /* silly magic number */
796 context->attr_names = g_realloc (context->attr_names, sizeof(char*)*context->alloc_attrs);
797 context->attr_values = g_realloc (context->attr_values, sizeof(char*)*context->alloc_attrs);
800 context->attr_names[context->cur_attr] = name;
801 context->attr_values[context->cur_attr] = NULL;
802 context->attr_names[context->cur_attr+1] = NULL;
803 context->attr_values[context->cur_attr+1] = NULL;
807 * g_markup_parse_context_parse:
808 * @context: a #GMarkupParseContext
809 * @text: chunk of text to parse
810 * @text_len: length of @text in bytes
811 * @error: return location for a #GError
813 * Feed some data to the #GMarkupParseContext. The data need not
814 * be valid UTF-8; an error will be signaled if it's invalid.
815 * The data need not be an entire document; you can feed a document
816 * into the parser incrementally, via multiple calls to this function.
817 * Typically, as you receive data from a network connection or file,
818 * you feed each received chunk of data into this function, aborting
819 * the process if an error occurs. Once an error is reported, no further
820 * data may be fed to the #GMarkupParseContext; all errors are fatal.
822 * Return value: %FALSE if an error occurred, %TRUE on success
825 g_markup_parse_context_parse (GMarkupParseContext *context,
830 const gchar *first_invalid;
832 g_return_val_if_fail (context != NULL, FALSE);
833 g_return_val_if_fail (text != NULL, FALSE);
834 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
835 g_return_val_if_fail (!context->parsing, FALSE);
838 text_len = strlen (text);
843 context->parsing = TRUE;
845 if (context->leftover_char_portion)
847 const gchar *first_char;
849 if ((*text & 0xc0) != 0x80)
852 first_char = g_utf8_find_next_char (text, text + text_len);
856 /* leftover_char_portion was completed. Parse it. */
857 GString *portion = context->leftover_char_portion;
859 g_string_append_len (context->leftover_char_portion,
860 text, first_char - text);
862 /* hacks to allow recursion */
863 context->parsing = FALSE;
864 context->leftover_char_portion = NULL;
866 if (!g_markup_parse_context_parse (context,
867 portion->str, portion->len,
870 g_assert (context->state == STATE_ERROR);
873 g_string_free (portion, TRUE);
874 context->parsing = TRUE;
876 /* Skip the fraction of char that was in this text */
877 text_len -= (first_char - text);
882 /* another little chunk of the leftover char; geez
883 * someone is inefficient.
885 g_string_append_len (context->leftover_char_portion,
888 if (context->leftover_char_portion->len > 7)
890 /* The leftover char portion is too big to be
895 G_MARKUP_ERROR_BAD_UTF8,
896 _("Invalid UTF-8 encoded text"));
903 context->current_text = text;
904 context->current_text_len = text_len;
905 context->iter = context->current_text;
906 context->start = context->iter;
908 /* Nothing left after finishing the leftover char, or nothing
909 * passed in to begin with.
911 if (context->current_text_len == 0)
914 /* find_current_text_end () assumes the string starts at
915 * a character start, so we need to validate at least
916 * that much. It doesn't assume any following bytes
919 if ((*context->current_text & 0xc0) == 0x80) /* not a char start */
923 G_MARKUP_ERROR_BAD_UTF8,
924 _("Invalid UTF-8 encoded text"));
928 /* Initialize context->current_text_end, possibly adjusting
929 * current_text_len, and add any leftover char portion
931 find_current_text_end (context);
933 /* Validate UTF8 (must be done after we find the end, since
934 * we could have a trailing incomplete char)
936 if (!g_utf8_validate (context->current_text,
937 context->current_text_len,
942 p = context->current_text;
943 while (p != context->current_text_end)
950 context->line_number += newlines;
954 G_MARKUP_ERROR_BAD_UTF8,
955 _("Invalid UTF-8 encoded text"));
959 while (context->iter != context->current_text_end)
961 switch (context->state)
964 /* Possible next state: AFTER_OPEN_ANGLE */
966 g_assert (context->tag_stack == NULL);
968 /* whitespace is ignored outside of any elements */
969 skip_spaces (context);
971 if (context->iter != context->current_text_end)
973 if (*context->iter == '<')
975 /* Move after the open angle */
976 advance_char (context);
978 context->state = STATE_AFTER_OPEN_ANGLE;
980 /* this could start a passthrough */
981 context->start = context->iter;
983 /* document is now non-empty */
984 context->document_empty = FALSE;
990 G_MARKUP_ERROR_PARSE,
991 _("Document must begin with an element (e.g. <book>)"));
996 case STATE_AFTER_OPEN_ANGLE:
997 /* Possible next states: INSIDE_OPEN_TAG_NAME,
998 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1000 if (*context->iter == '?' ||
1001 *context->iter == '!')
1003 /* include < in the passthrough */
1004 const gchar *openangle = "<";
1005 add_to_partial (context, openangle, openangle + 1);
1006 context->start = context->iter;
1007 context->balance = 1;
1008 context->state = STATE_INSIDE_PASSTHROUGH;
1010 else if (*context->iter == '/')
1013 advance_char (context);
1015 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1017 else if (is_name_start_char (g_utf8_get_char (context->iter)))
1019 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1021 /* start of tag name */
1022 context->start = context->iter;
1029 G_MARKUP_ERROR_PARSE,
1030 _("'%s' is not a valid character following "
1031 "a '<' character; it may not begin an "
1033 utf8_str (context->iter, buf));
1037 /* The AFTER_CLOSE_ANGLE state is actually sort of
1038 * broken, because it doesn't correspond to a range
1039 * of characters in the input stream as the others do,
1040 * and thus makes things harder to conceptualize
1042 case STATE_AFTER_CLOSE_ANGLE:
1043 /* Possible next states: INSIDE_TEXT, STATE_START */
1044 if (context->tag_stack == NULL)
1046 context->start = NULL;
1047 context->state = STATE_START;
1051 context->start = context->iter;
1052 context->state = STATE_INSIDE_TEXT;
1056 case STATE_AFTER_ELISION_SLASH:
1057 /* Possible next state: AFTER_CLOSE_ANGLE */
1060 /* We need to pop the tag stack and call the end_element
1061 * function, since this is the close tag
1063 GError *tmp_error = NULL;
1065 g_assert (context->tag_stack != NULL);
1068 if (context->parser->end_element)
1069 (* context->parser->end_element) (context,
1070 context->tag_stack->data,
1076 mark_error (context, tmp_error);
1077 g_propagate_error (error, tmp_error);
1081 if (*context->iter == '>')
1083 /* move after the close angle */
1084 advance_char (context);
1085 context->state = STATE_AFTER_CLOSE_ANGLE;
1092 G_MARKUP_ERROR_PARSE,
1093 _("Odd character '%s', expected a '>' character "
1094 "to end the start tag of element '%s'"),
1095 utf8_str (context->iter, buf),
1096 current_element (context));
1100 g_free (context->tag_stack->data);
1101 context->tag_stack = g_slist_delete_link (context->tag_stack,
1102 context->tag_stack);
1106 case STATE_INSIDE_OPEN_TAG_NAME:
1107 /* Possible next states: BETWEEN_ATTRIBUTES */
1109 /* if there's a partial chunk then it's the first part of the
1110 * tag name. If there's a context->start then it's the start
1111 * of the tag name in current_text, the partial chunk goes
1112 * before that start though.
1114 advance_to_name_end (context);
1116 if (context->iter == context->current_text_end)
1118 /* The name hasn't necessarily ended. Merge with
1119 * partial chunk, leave state unchanged.
1121 add_to_partial (context, context->start, context->iter);
1125 /* The name has ended. Combine it with the partial chunk
1126 * if any; push it on the stack; enter next state.
1128 add_to_partial (context, context->start, context->iter);
1129 context->tag_stack =
1130 g_slist_prepend (context->tag_stack,
1131 g_string_free (context->partial_chunk,
1134 context->partial_chunk = NULL;
1136 context->state = STATE_BETWEEN_ATTRIBUTES;
1137 context->start = NULL;
1141 case STATE_INSIDE_ATTRIBUTE_NAME:
1142 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1144 advance_to_name_end (context);
1145 add_to_partial (context, context->start, context->iter);
1147 /* read the full name, if we enter the equals sign state
1148 * then add the attribute to the list (without the value),
1149 * otherwise store a partial chunk to be prepended later.
1151 if (context->iter != context->current_text_end)
1152 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1155 case STATE_AFTER_ATTRIBUTE_NAME:
1156 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1158 skip_spaces (context);
1160 if (context->iter != context->current_text_end)
1162 /* The name has ended. Combine it with the partial chunk
1163 * if any; push it on the stack; enter next state.
1165 add_attribute (context, g_string_free (context->partial_chunk, FALSE));
1167 context->partial_chunk = NULL;
1168 context->start = NULL;
1170 if (*context->iter == '=')
1172 advance_char (context);
1173 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1180 G_MARKUP_ERROR_PARSE,
1181 _("Odd character '%s', expected a '=' after "
1182 "attribute name '%s' of element '%s'"),
1183 utf8_str (context->iter, buf),
1184 current_attribute (context),
1185 current_element (context));
1191 case STATE_BETWEEN_ATTRIBUTES:
1192 /* Possible next states: AFTER_CLOSE_ANGLE,
1193 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1195 skip_spaces (context);
1197 if (context->iter != context->current_text_end)
1199 if (*context->iter == '/')
1201 advance_char (context);
1202 context->state = STATE_AFTER_ELISION_SLASH;
1204 else if (*context->iter == '>')
1207 advance_char (context);
1208 context->state = STATE_AFTER_CLOSE_ANGLE;
1210 else if (is_name_start_char (g_utf8_get_char (context->iter)))
1212 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1213 /* start of attribute name */
1214 context->start = context->iter;
1221 G_MARKUP_ERROR_PARSE,
1222 _("Odd character '%s', expected a '>' or '/' "
1223 "character to end the start tag of "
1224 "element '%s', or optionally an attribute; "
1225 "perhaps you used an invalid character in "
1226 "an attribute name"),
1227 utf8_str (context->iter, buf),
1228 current_element (context));
1231 /* If we're done with attributes, invoke
1232 * the start_element callback
1234 if (context->state == STATE_AFTER_ELISION_SLASH ||
1235 context->state == STATE_AFTER_CLOSE_ANGLE)
1237 const gchar *start_name;
1238 /* Ugly, but the current code expects an empty array instead of NULL */
1239 const gchar *empty = NULL;
1240 const gchar **attr_names = ∅
1241 const gchar **attr_values = ∅
1244 /* Call user callback for element start */
1245 start_name = current_element (context);
1247 if (context->cur_attr >= 0)
1249 attr_names = (const gchar**)context->attr_names;
1250 attr_values = (const gchar**)context->attr_values;
1254 if (context->parser->start_element)
1255 (* context->parser->start_element) (context,
1257 (const gchar **)attr_names,
1258 (const gchar **)attr_values,
1262 /* Go ahead and free the attributes. */
1263 for (; context->cur_attr >= 0; context->cur_attr--)
1265 int pos = context->cur_attr;
1266 g_free (context->attr_names[pos]);
1267 g_free (context->attr_values[pos]);
1268 context->attr_names[pos] = context->attr_values[pos] = NULL;
1270 g_assert (context->cur_attr == -1);
1271 g_assert (context->attr_names == NULL ||
1272 context->attr_names[0] == NULL);
1273 g_assert (context->attr_values == NULL ||
1274 context->attr_values[0] == NULL);
1276 if (tmp_error != NULL)
1278 mark_error (context, tmp_error);
1279 g_propagate_error (error, tmp_error);
1285 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1286 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1288 skip_spaces (context);
1290 if (context->iter != context->current_text_end)
1292 if (*context->iter == '"')
1294 advance_char (context);
1295 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1296 context->start = context->iter;
1298 else if (*context->iter == '\'')
1300 advance_char (context);
1301 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1302 context->start = context->iter;
1309 G_MARKUP_ERROR_PARSE,
1310 _("Odd character '%s', expected an open quote mark "
1311 "after the equals sign when giving value for "
1312 "attribute '%s' of element '%s'"),
1313 utf8_str (context->iter, buf),
1314 current_attribute (context),
1315 current_element (context));
1320 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1321 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1322 /* Possible next states: BETWEEN_ATTRIBUTES */
1326 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1337 if (*context->iter == delim)
1340 while (advance_char (context));
1342 if (context->iter == context->current_text_end)
1344 /* The value hasn't necessarily ended. Merge with
1345 * partial chunk, leave state unchanged.
1347 add_to_partial (context, context->start, context->iter);
1351 /* The value has ended at the quote mark. Combine it
1352 * with the partial chunk if any; set it for the current
1355 add_to_partial (context, context->start, context->iter);
1357 g_assert (context->cur_attr >= 0);
1359 if (unescape_text (context,
1360 context->partial_chunk->str,
1361 context->partial_chunk->str +
1362 context->partial_chunk->len,
1363 &context->attr_values[context->cur_attr],
1366 /* success, advance past quote and set state. */
1367 advance_char (context);
1368 context->state = STATE_BETWEEN_ATTRIBUTES;
1369 context->start = NULL;
1372 truncate_partial (context);
1376 case STATE_INSIDE_TEXT:
1377 /* Possible next states: AFTER_OPEN_ANGLE */
1380 if (*context->iter == '<')
1383 while (advance_char (context));
1385 /* The text hasn't necessarily ended. Merge with
1386 * partial chunk, leave state unchanged.
1389 add_to_partial (context, context->start, context->iter);
1391 if (context->iter != context->current_text_end)
1393 gchar *unescaped = NULL;
1395 /* The text has ended at the open angle. Call the text
1399 if (unescape_text (context,
1400 context->partial_chunk->str,
1401 context->partial_chunk->str +
1402 context->partial_chunk->len,
1406 GError *tmp_error = NULL;
1408 if (context->parser->text)
1409 (*context->parser->text) (context,
1417 if (tmp_error == NULL)
1419 /* advance past open angle and set state. */
1420 advance_char (context);
1421 context->state = STATE_AFTER_OPEN_ANGLE;
1422 /* could begin a passthrough */
1423 context->start = context->iter;
1427 mark_error (context, tmp_error);
1428 g_propagate_error (error, tmp_error);
1432 truncate_partial (context);
1436 case STATE_AFTER_CLOSE_TAG_SLASH:
1437 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1438 if (is_name_start_char (g_utf8_get_char (context->iter)))
1440 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1442 /* start of tag name */
1443 context->start = context->iter;
1450 G_MARKUP_ERROR_PARSE,
1451 _("'%s' is not a valid character following "
1452 "the characters '</'; '%s' may not begin an "
1454 utf8_str (context->iter, buf),
1455 utf8_str (context->iter, buf));
1459 case STATE_INSIDE_CLOSE_TAG_NAME:
1460 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1461 advance_to_name_end (context);
1462 add_to_partial (context, context->start, context->iter);
1464 if (context->iter != context->current_text_end)
1465 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1468 case STATE_AFTER_CLOSE_TAG_NAME:
1469 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1471 skip_spaces (context);
1473 if (context->iter != context->current_text_end)
1477 /* The name has ended. Combine it with the partial chunk
1478 * if any; check that it matches stack top and pop
1479 * stack; invoke proper callback; enter next state.
1481 close_name = g_string_free (context->partial_chunk, FALSE);
1482 context->partial_chunk = NULL;
1484 if (*context->iter != '>')
1489 G_MARKUP_ERROR_PARSE,
1490 _("'%s' is not a valid character following "
1491 "the close element name '%s'; the allowed "
1492 "character is '>'"),
1493 utf8_str (context->iter, buf),
1496 else if (context->tag_stack == NULL)
1500 G_MARKUP_ERROR_PARSE,
1501 _("Element '%s' was closed, no element "
1502 "is currently open"),
1505 else if (strcmp (close_name, current_element (context)) != 0)
1509 G_MARKUP_ERROR_PARSE,
1510 _("Element '%s' was closed, but the currently "
1511 "open element is '%s'"),
1513 current_element (context));
1518 advance_char (context);
1519 context->state = STATE_AFTER_CLOSE_ANGLE;
1520 context->start = NULL;
1522 /* call the end_element callback */
1524 if (context->parser->end_element)
1525 (* context->parser->end_element) (context,
1531 /* Pop the tag stack */
1532 g_free (context->tag_stack->data);
1533 context->tag_stack = g_slist_delete_link (context->tag_stack,
1534 context->tag_stack);
1538 mark_error (context, tmp_error);
1539 g_propagate_error (error, tmp_error);
1543 g_free (close_name);
1547 case STATE_INSIDE_PASSTHROUGH:
1548 /* Possible next state: AFTER_CLOSE_ANGLE */
1551 if (*context->iter == '<')
1553 if (*context->iter == '>')
1556 add_to_partial (context, context->start, context->iter);
1557 context->start = context->iter;
1558 if ((g_str_has_prefix (context->partial_chunk->str, "<?")
1559 && g_str_has_suffix (context->partial_chunk->str, "?")) ||
1560 (g_str_has_prefix (context->partial_chunk->str, "<!--")
1561 && g_str_has_suffix (context->partial_chunk->str, "--")) ||
1562 (g_str_has_prefix (context->partial_chunk->str, "<![CDATA[")
1563 && g_str_has_suffix (context->partial_chunk->str, "]]")) ||
1564 (g_str_has_prefix (context->partial_chunk->str, "<!DOCTYPE")
1565 && context->balance == 0))
1569 while (advance_char (context));
1571 if (context->iter == context->current_text_end)
1573 /* The passthrough hasn't necessarily ended. Merge with
1574 * partial chunk, leave state unchanged.
1576 add_to_partial (context, context->start, context->iter);
1580 /* The passthrough has ended at the close angle. Combine
1581 * it with the partial chunk if any. Call the passthrough
1582 * callback. Note that the open/close angles are
1583 * included in the text of the passthrough.
1585 GError *tmp_error = NULL;
1587 advance_char (context); /* advance past close angle */
1588 add_to_partial (context, context->start, context->iter);
1590 if (context->parser->passthrough)
1591 (*context->parser->passthrough) (context,
1592 context->partial_chunk->str,
1593 context->partial_chunk->len,
1597 truncate_partial (context);
1599 if (tmp_error == NULL)
1601 context->state = STATE_AFTER_CLOSE_ANGLE;
1602 context->start = context->iter; /* could begin text */
1606 mark_error (context, tmp_error);
1607 g_propagate_error (error, tmp_error);
1617 g_assert_not_reached ();
1623 context->parsing = FALSE;
1625 return context->state != STATE_ERROR;
1629 * g_markup_parse_context_end_parse:
1630 * @context: a #GMarkupParseContext
1631 * @error: return location for a #GError
1633 * Signals to the #GMarkupParseContext that all data has been
1634 * fed into the parse context with g_markup_parse_context_parse().
1635 * This function reports an error if the document isn't complete,
1636 * for example if elements are still open.
1638 * Return value: %TRUE on success, %FALSE if an error was set
1641 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1644 g_return_val_if_fail (context != NULL, FALSE);
1645 g_return_val_if_fail (!context->parsing, FALSE);
1646 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1648 if (context->partial_chunk != NULL)
1650 g_string_free (context->partial_chunk, TRUE);
1651 context->partial_chunk = NULL;
1654 if (context->document_empty)
1656 set_error (context, error, G_MARKUP_ERROR_EMPTY,
1657 _("Document was empty or contained only whitespace"));
1661 context->parsing = TRUE;
1663 switch (context->state)
1669 case STATE_AFTER_OPEN_ANGLE:
1670 set_error (context, error, G_MARKUP_ERROR_PARSE,
1671 _("Document ended unexpectedly just after an open angle bracket '<'"));
1674 case STATE_AFTER_CLOSE_ANGLE:
1675 if (context->tag_stack != NULL)
1677 /* Error message the same as for INSIDE_TEXT */
1678 set_error (context, error, G_MARKUP_ERROR_PARSE,
1679 _("Document ended unexpectedly with elements still open - "
1680 "'%s' was the last element opened"),
1681 current_element (context));
1685 case STATE_AFTER_ELISION_SLASH:
1686 set_error (context, error, G_MARKUP_ERROR_PARSE,
1687 _("Document ended unexpectedly, expected to see a close angle "
1688 "bracket ending the tag <%s/>"), current_element (context));
1691 case STATE_INSIDE_OPEN_TAG_NAME:
1692 set_error (context, error, G_MARKUP_ERROR_PARSE,
1693 _("Document ended unexpectedly inside an element name"));
1696 case STATE_INSIDE_ATTRIBUTE_NAME:
1697 set_error (context, error, G_MARKUP_ERROR_PARSE,
1698 _("Document ended unexpectedly inside an attribute name"));
1701 case STATE_BETWEEN_ATTRIBUTES:
1702 set_error (context, error, G_MARKUP_ERROR_PARSE,
1703 _("Document ended unexpectedly inside an element-opening "
1707 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1708 set_error (context, error, G_MARKUP_ERROR_PARSE,
1709 _("Document ended unexpectedly after the equals sign "
1710 "following an attribute name; no attribute value"));
1713 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1714 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1715 set_error (context, error, G_MARKUP_ERROR_PARSE,
1716 _("Document ended unexpectedly while inside an attribute "
1720 case STATE_INSIDE_TEXT:
1721 g_assert (context->tag_stack != NULL);
1722 set_error (context, error, G_MARKUP_ERROR_PARSE,
1723 _("Document ended unexpectedly with elements still open - "
1724 "'%s' was the last element opened"),
1725 current_element (context));
1728 case STATE_AFTER_CLOSE_TAG_SLASH:
1729 case STATE_INSIDE_CLOSE_TAG_NAME:
1730 set_error (context, error, G_MARKUP_ERROR_PARSE,
1731 _("Document ended unexpectedly inside the close tag for "
1732 "element '%s'"), current_element);
1735 case STATE_INSIDE_PASSTHROUGH:
1736 set_error (context, error, G_MARKUP_ERROR_PARSE,
1737 _("Document ended unexpectedly inside a comment or "
1738 "processing instruction"));
1743 g_assert_not_reached ();
1747 context->parsing = FALSE;
1749 return context->state != STATE_ERROR;
1753 * g_markup_parse_context_get_element:
1754 * @context: a #GMarkupParseContext
1755 * @returns: the name of the currently open element, or %NULL
1757 * Retrieves the name of the currently open element.
1761 G_CONST_RETURN gchar *
1762 g_markup_parse_context_get_element (GMarkupParseContext *context)
1764 g_return_val_if_fail (context != NULL, NULL);
1766 if (context->tag_stack == NULL)
1769 return current_element (context);
1773 * g_markup_parse_context_get_position:
1774 * @context: a #GMarkupParseContext
1775 * @line_number: return location for a line number, or %NULL
1776 * @char_number: return location for a char-on-line number, or %NULL
1778 * Retrieves the current line number and the number of the character on
1779 * that line. Intended for use in error messages; there are no strict
1780 * semantics for what constitutes the "current" line number other than
1781 * "the best number we could come up with for error messages."
1785 g_markup_parse_context_get_position (GMarkupParseContext *context,
1789 g_return_if_fail (context != NULL);
1792 *line_number = context->line_number;
1795 *char_number = context->char_number;
1799 append_escaped_text (GString *str,
1807 end = text + length;
1812 next = g_utf8_next_char (p);
1817 g_string_append (str, "&");
1821 g_string_append (str, "<");
1825 g_string_append (str, ">");
1829 g_string_append (str, "'");
1833 g_string_append (str, """);
1837 g_string_append_len (str, p, next - p);
1846 * g_markup_escape_text:
1847 * @text: some valid UTF-8 text
1848 * @length: length of @text in bytes
1850 * Escapes text so that the markup parser will parse it verbatim.
1851 * Less than, greater than, ampersand, etc. are replaced with the
1852 * corresponding entities. This function would typically be used
1853 * when writing out a file to be parsed with the markup parser.
1855 * Note that this function doesn't protect whitespace and line endings
1856 * from being processed according to the XML rules for normalization
1857 * of line endings and attribute values.
1859 * Return value: escaped text
1862 g_markup_escape_text (const gchar *text,
1867 g_return_val_if_fail (text != NULL, NULL);
1870 length = strlen (text);
1872 str = g_string_new (NULL);
1873 append_escaped_text (str, text, length);
1875 return g_string_free (str, FALSE);
1880 * @format: a printf-style format string
1881 * @after: location to store a pointer to the character after
1882 * the returned conversion. On a %NULL return, returns the
1883 * pointer to the trailing NUL in the string
1885 * Find the next conversion in a printf-style format string.
1886 * Partially based on code from printf-parser.c,
1887 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
1889 * Return value: pointer to the next conversion in @format,
1890 * or %NULL, if none.
1893 find_conversion (const char *format,
1896 const char *start = format;
1899 while (*start != '\0' && *start != '%')
1916 /* Test for positional argument. */
1917 if (*cp >= '0' && *cp <= '9')
1921 for (np = cp; *np >= '0' && *np <= '9'; np++)
1927 /* Skip the flags. */
1941 /* Skip the field width. */
1946 /* Test for positional argument. */
1947 if (*cp >= '0' && *cp <= '9')
1951 for (np = cp; *np >= '0' && *np <= '9'; np++)
1959 for (; *cp >= '0' && *cp <= '9'; cp++)
1963 /* Skip the precision. */
1969 /* Test for positional argument. */
1970 if (*cp >= '0' && *cp <= '9')
1974 for (np = cp; *np >= '0' && *np <= '9'; np++)
1982 for (; *cp >= '0' && *cp <= '9'; cp++)
1987 /* Skip argument type/size specifiers. */
1988 while (*cp == 'h' ||
1997 /* Skip the conversion character. */
2005 * g_markup_vprintf_escaped:
2006 * @format: printf() style format string
2007 * @args: variable argument list, similar to vprintf()
2009 * Formats the data in @args according to @format, escaping
2010 * all string and character arguments in the fashion
2011 * of g_markup_escape_text(). See g_markup_printf_escaped().
2013 * Return value: newly allocated result from formatting
2014 * operation. Free with g_free().
2019 g_markup_vprintf_escaped (const char *format,
2024 GString *result = NULL;
2025 gchar *output1 = NULL;
2026 gchar *output2 = NULL;
2027 const char *p, *op1, *op2;
2030 /* The technique here, is that we make two format strings that
2031 * have the identical conversions in the identical order to the
2032 * original strings, but differ in the text in-between. We
2033 * then use the normal g_strdup_vprintf() to format the arguments
2034 * with the two new format strings. By comparing the results,
2035 * we can figure out what segments of the output come from
2036 * the the original format string, and what from the arguments,
2037 * and thus know what portions of the string to escape.
2039 * For instance, for:
2041 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2043 * We form the two format strings "%sX%dX" and %sY%sY". The results
2044 * of formatting with those two strings are
2046 * "%sX%dX" => "Susan & FredX5X"
2047 * "%sY%dY" => "Susan & FredY5Y"
2049 * To find the span of the first argument, we find the first position
2050 * where the two arguments differ, which tells us that the first
2051 * argument formatted to "Susan & Fred". We then escape that
2052 * to "Susan & Fred" and join up with the intermediate portions
2053 * of the format string and the second argument to get
2054 * "Susan & Fred ate 5 apples".
2057 /* Create the two modified format strings
2059 format1 = g_string_new (NULL);
2060 format2 = g_string_new (NULL);
2065 const char *conv = find_conversion (p, &after);
2069 g_string_append_len (format1, conv, after - conv);
2070 g_string_append_c (format1, 'X');
2071 g_string_append_len (format2, conv, after - conv);
2072 g_string_append_c (format2, 'Y');
2077 /* Use them to format the arguments
2079 G_VA_COPY (args2, args);
2081 output1 = g_strdup_vprintf (format1->str, args);
2086 output2 = g_strdup_vprintf (format2->str, args2);
2091 result = g_string_new (NULL);
2093 /* Iterate through the original format string again,
2094 * copying the non-conversion portions and the escaped
2095 * converted arguments to the output string.
2103 const char *output_start;
2104 const char *conv = find_conversion (p, &after);
2107 if (!conv) /* The end, after points to the trailing \0 */
2109 g_string_append_len (result, p, after - p);
2113 g_string_append_len (result, p, conv - p);
2115 while (*op1 == *op2)
2121 escaped = g_markup_escape_text (output_start, op1 - output_start);
2122 g_string_append (result, escaped);
2131 g_string_free (format1, TRUE);
2132 g_string_free (format2, TRUE);
2137 return g_string_free (result, FALSE);
2143 * g_markup_printf_escaped:
2144 * @format: printf() style format string
2145 * @Varargs: the arguments to insert in the format string
2147 * Formats arguments according to @format, escaping
2148 * all string and character arguments in the fashion
2149 * of g_markup_escape_text(). This is useful when you
2150 * want to insert literal strings into XML-style markup
2151 * output, without having to worry that the strings
2152 * might themselves contain markup.
2154 * <informalexample><programlisting>
2155 * const char *store = "Fortnum & Mason";
2156 * const char *item = "Tea";
2159 * output = g_markup_printf_escaped ("<purchase>"
2160 * "<store>%s</store>"
2161 * "<item>%s</item>"
2162 * "</purchase>",
2164 * </programlisting></informalexample>
2166 * Return value: newly allocated result from formatting
2167 * operation. Free with g_free().
2172 g_markup_printf_escaped (const char *format, ...)
2177 va_start (args, format);
2178 result = g_markup_vprintf_escaped (format, args);