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);
209 static void set_error (GMarkupParseContext *context,
213 ...) G_GNUC_PRINTF (4, 5);
216 set_error (GMarkupParseContext *context,
226 va_start (args, format);
227 s = g_strdup_vprintf (format, args);
230 tmp_error = g_error_new (G_MARKUP_ERROR,
232 _("Error on line %d char %d: %s"),
233 context->line_number,
234 context->char_number,
239 mark_error (context, tmp_error);
241 g_propagate_error (error, tmp_error);
245 /* To make these faster, we first use the ascii-only tests, then check
246 * for the usual non-alnum name-end chars, and only then call the
247 * expensive unicode stuff. Nobody uses non-ascii in XML tag/attribute
248 * names, so this is a reasonable hack that virtually always avoids
251 #define IS_COMMON_NAME_END_CHAR(c) \
252 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
255 is_name_start_char (const gchar *p)
257 if (g_ascii_isalpha (*p) ||
258 (!IS_COMMON_NAME_END_CHAR (*p) &&
261 g_unichar_isalpha (g_utf8_get_char (p)))))
268 is_name_char (const gchar *p)
270 if (g_ascii_isalnum (*p) ||
271 (!IS_COMMON_NAME_END_CHAR (*p) &&
276 g_unichar_isalpha (g_utf8_get_char (p)))))
284 char_str (gunichar c,
288 g_unichar_to_utf8 (c, buf);
293 utf8_str (const gchar *utf8,
296 char_str (g_utf8_get_char (utf8), buf);
301 set_unescape_error (GMarkupParseContext *context,
303 const gchar *remaining_text,
304 const gchar *remaining_text_end,
312 gint remaining_newlines;
315 remaining_newlines = 0;
317 while (p != remaining_text_end)
320 ++remaining_newlines;
324 va_start (args, format);
325 s = g_strdup_vprintf (format, args);
328 tmp_error = g_error_new (G_MARKUP_ERROR,
330 _("Error on line %d: %s"),
331 context->line_number - remaining_newlines,
336 mark_error (context, tmp_error);
338 g_propagate_error (error, tmp_error);
344 USTATE_AFTER_AMPERSAND,
345 USTATE_INSIDE_ENTITY_NAME,
346 USTATE_AFTER_CHARREF_HASH
351 GMarkupParseContext *context;
355 const gchar *text_end;
356 const gchar *entity_start;
360 unescape_text_state_inside_text (UnescapeContext *ucontext,
365 gboolean normalize_attribute;
367 if (ucontext->context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
368 ucontext->context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
369 normalize_attribute = TRUE;
371 normalize_attribute = FALSE;
375 while (p != ucontext->text_end)
381 else if (normalize_attribute && (*p == '\t' || *p == '\n'))
383 g_string_append_len (ucontext->str, start, p - start);
384 g_string_append_c (ucontext->str, ' ');
385 p = g_utf8_next_char (p);
390 g_string_append_len (ucontext->str, start, p - start);
391 g_string_append_c (ucontext->str, normalize_attribute ? ' ' : '\n');
392 p = g_utf8_next_char (p);
393 if (p != ucontext->text_end && *p == '\n')
394 p = g_utf8_next_char (p);
398 p = g_utf8_next_char (p);
402 g_string_append_len (ucontext->str, start, p - start);
404 if (p != ucontext->text_end && *p == '&')
406 p = g_utf8_next_char (p);
407 ucontext->state = USTATE_AFTER_AMPERSAND;
414 unescape_text_state_after_ampersand (UnescapeContext *ucontext,
418 ucontext->entity_start = NULL;
422 p = g_utf8_next_char (p);
424 ucontext->entity_start = p;
425 ucontext->state = USTATE_AFTER_CHARREF_HASH;
427 else if (!is_name_start_char (p))
431 set_unescape_error (ucontext->context, error,
432 p, ucontext->text_end,
433 G_MARKUP_ERROR_PARSE,
434 _("Empty entity '&;' seen; valid "
435 "entities are: & " < > '"));
441 set_unescape_error (ucontext->context, error,
442 p, ucontext->text_end,
443 G_MARKUP_ERROR_PARSE,
444 _("Character '%s' is not valid at "
445 "the start of an entity name; "
446 "the & character begins an entity; "
447 "if this ampersand isn't supposed "
448 "to be an entity, escape it as "
455 ucontext->entity_start = p;
456 ucontext->state = USTATE_INSIDE_ENTITY_NAME;
463 unescape_text_state_inside_entity_name (UnescapeContext *ucontext,
467 while (p != ucontext->text_end)
471 else if (!is_name_char (p))
475 set_unescape_error (ucontext->context, error,
476 p, ucontext->text_end,
477 G_MARKUP_ERROR_PARSE,
478 _("Character '%s' is not valid "
479 "inside an entity name"),
484 p = g_utf8_next_char (p);
487 if (ucontext->context->state != STATE_ERROR)
489 if (p != ucontext->text_end)
491 gint len = p - ucontext->entity_start;
493 /* move to after semicolon */
494 p = g_utf8_next_char (p);
495 ucontext->state = USTATE_INSIDE_TEXT;
497 if (strncmp (ucontext->entity_start, "lt", len) == 0)
498 g_string_append_c (ucontext->str, '<');
499 else if (strncmp (ucontext->entity_start, "gt", len) == 0)
500 g_string_append_c (ucontext->str, '>');
501 else if (strncmp (ucontext->entity_start, "amp", len) == 0)
502 g_string_append_c (ucontext->str, '&');
503 else if (strncmp (ucontext->entity_start, "quot", len) == 0)
504 g_string_append_c (ucontext->str, '"');
505 else if (strncmp (ucontext->entity_start, "apos", len) == 0)
506 g_string_append_c (ucontext->str, '\'');
511 name = g_strndup (ucontext->entity_start, len);
512 set_unescape_error (ucontext->context, error,
513 p, ucontext->text_end,
514 G_MARKUP_ERROR_PARSE,
515 _("Entity name '%s' is not known"),
522 set_unescape_error (ucontext->context, error,
523 /* give line number of the & */
524 ucontext->entity_start, ucontext->text_end,
525 G_MARKUP_ERROR_PARSE,
526 _("Entity did not end with a semicolon; "
527 "most likely you used an ampersand "
528 "character without intending to start "
529 "an entity - escape ampersand as &"));
538 unescape_text_state_after_charref_hash (UnescapeContext *ucontext,
542 gboolean is_hex = FALSE;
545 start = ucontext->entity_start;
550 p = g_utf8_next_char (p);
554 while (p != ucontext->text_end && *p != ';')
555 p = g_utf8_next_char (p);
557 if (p != ucontext->text_end)
559 g_assert (*p == ';');
561 /* digit is between start and p */
570 l = strtoul (start, &end, 16);
572 l = strtoul (start, &end, 10);
574 if (end != p || errno != 0)
576 set_unescape_error (ucontext->context, error,
577 start, ucontext->text_end,
578 G_MARKUP_ERROR_PARSE,
579 _("Failed to parse '%-.*s', which "
580 "should have been a digit "
581 "inside a character reference "
582 "(ê for example) - perhaps "
583 "the digit is too large"),
588 /* characters XML permits */
592 (l >= 0x20 && l <= 0xD7FF) ||
593 (l >= 0xE000 && l <= 0xFFFD) ||
594 (l >= 0x10000 && l <= 0x10FFFF))
597 g_string_append (ucontext->str, char_str (l, buf));
601 set_unescape_error (ucontext->context, error,
602 start, ucontext->text_end,
603 G_MARKUP_ERROR_PARSE,
604 _("Character reference '%-.*s' does not "
605 "encode a permitted character"),
610 /* Move to next state */
611 p = g_utf8_next_char (p); /* past semicolon */
612 ucontext->state = USTATE_INSIDE_TEXT;
616 set_unescape_error (ucontext->context, error,
617 start, ucontext->text_end,
618 G_MARKUP_ERROR_PARSE,
619 _("Empty character reference; "
620 "should include a digit such as "
626 set_unescape_error (ucontext->context, error,
627 start, ucontext->text_end,
628 G_MARKUP_ERROR_PARSE,
629 _("Character reference did not end with a "
631 "most likely you used an ampersand "
632 "character without intending to start "
633 "an entity - escape ampersand as &"));
640 unescape_text (GMarkupParseContext *context,
642 const gchar *text_end,
646 UnescapeContext ucontext;
649 ucontext.context = context;
650 ucontext.text = text;
651 ucontext.text_end = text_end;
652 ucontext.entity_start = NULL;
654 ucontext.str = g_string_sized_new (text_end - text);
656 ucontext.state = USTATE_INSIDE_TEXT;
659 while (p != text_end && context->state != STATE_ERROR)
661 g_assert (p < text_end);
663 switch (ucontext.state)
665 case USTATE_INSIDE_TEXT:
667 p = unescape_text_state_inside_text (&ucontext,
673 case USTATE_AFTER_AMPERSAND:
675 p = unescape_text_state_after_ampersand (&ucontext,
682 case USTATE_INSIDE_ENTITY_NAME:
684 p = unescape_text_state_inside_entity_name (&ucontext,
690 case USTATE_AFTER_CHARREF_HASH:
692 p = unescape_text_state_after_charref_hash (&ucontext,
699 g_assert_not_reached ();
704 if (context->state != STATE_ERROR)
706 switch (ucontext.state)
708 case USTATE_INSIDE_TEXT:
710 case USTATE_AFTER_AMPERSAND:
711 case USTATE_INSIDE_ENTITY_NAME:
712 set_unescape_error (context, error,
714 G_MARKUP_ERROR_PARSE,
715 _("Unfinished entity reference"));
717 case USTATE_AFTER_CHARREF_HASH:
718 set_unescape_error (context, error,
720 G_MARKUP_ERROR_PARSE,
721 _("Unfinished character reference"));
726 if (context->state == STATE_ERROR)
728 g_string_free (ucontext.str, TRUE);
734 *unescaped = ucontext.str;
739 static inline gboolean
740 advance_char (GMarkupParseContext *context)
742 context->iter = g_utf8_next_char (context->iter);
743 context->char_number += 1;
745 if (context->iter == context->current_text_end)
749 else if (*context->iter == '\n')
751 context->line_number += 1;
752 context->char_number = 1;
758 static inline gboolean
761 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
765 skip_spaces (GMarkupParseContext *context)
769 if (!xml_isspace (*context->iter))
772 while (advance_char (context));
776 advance_to_name_end (GMarkupParseContext *context)
780 if (!is_name_char (context->iter))
783 while (advance_char (context));
787 add_to_partial (GMarkupParseContext *context,
788 const gchar *text_start,
789 const gchar *text_end)
791 if (context->partial_chunk == NULL)
792 context->partial_chunk = g_string_sized_new (text_end - text_start);
794 if (text_start != text_end)
795 g_string_append_len (context->partial_chunk, text_start,
796 text_end - text_start);
798 /* Invariant here that partial_chunk exists */
802 truncate_partial (GMarkupParseContext *context)
804 if (context->partial_chunk != NULL)
806 context->partial_chunk = g_string_truncate (context->partial_chunk, 0);
811 current_element (GMarkupParseContext *context)
813 return context->tag_stack->data;
817 current_attribute (GMarkupParseContext *context)
819 g_assert (context->cur_attr >= 0);
820 return context->attr_names[context->cur_attr];
824 find_current_text_end (GMarkupParseContext *context)
826 /* This function must be safe (non-segfaulting) on invalid UTF8.
827 * It assumes the string starts with a character start
829 const gchar *end = context->current_text + context->current_text_len;
833 g_assert (context->current_text_len > 0);
835 p = g_utf8_find_prev_char (context->current_text, end);
837 g_assert (p != NULL); /* since current_text was a char start */
839 /* p is now the start of the last character or character portion. */
841 next = g_utf8_next_char (p); /* this only touches *p, nothing beyond */
845 /* whole character */
846 context->current_text_end = end;
851 context->leftover_char_portion = g_string_new_len (p, end - p);
852 context->current_text_len -= (end - p);
853 context->current_text_end = p;
859 add_attribute (GMarkupParseContext *context, char *name)
861 if (context->cur_attr + 2 >= context->alloc_attrs)
863 context->alloc_attrs += 5; /* silly magic number */
864 context->attr_names = g_realloc (context->attr_names, sizeof(char*)*context->alloc_attrs);
865 context->attr_values = g_realloc (context->attr_values, sizeof(char*)*context->alloc_attrs);
868 context->attr_names[context->cur_attr] = name;
869 context->attr_values[context->cur_attr] = NULL;
870 context->attr_names[context->cur_attr+1] = NULL;
871 context->attr_values[context->cur_attr+1] = NULL;
875 * g_markup_parse_context_parse:
876 * @context: a #GMarkupParseContext
877 * @text: chunk of text to parse
878 * @text_len: length of @text in bytes
879 * @error: return location for a #GError
881 * Feed some data to the #GMarkupParseContext. The data need not
882 * be valid UTF-8; an error will be signaled if it's invalid.
883 * The data need not be an entire document; you can feed a document
884 * into the parser incrementally, via multiple calls to this function.
885 * Typically, as you receive data from a network connection or file,
886 * you feed each received chunk of data into this function, aborting
887 * the process if an error occurs. Once an error is reported, no further
888 * data may be fed to the #GMarkupParseContext; all errors are fatal.
890 * Return value: %FALSE if an error occurred, %TRUE on success
893 g_markup_parse_context_parse (GMarkupParseContext *context,
898 const gchar *first_invalid;
900 g_return_val_if_fail (context != NULL, FALSE);
901 g_return_val_if_fail (text != NULL, FALSE);
902 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
903 g_return_val_if_fail (!context->parsing, FALSE);
906 text_len = strlen (text);
911 context->parsing = TRUE;
913 if (context->leftover_char_portion)
915 const gchar *first_char;
917 if ((*text & 0xc0) != 0x80)
920 first_char = g_utf8_find_next_char (text, text + text_len);
924 /* leftover_char_portion was completed. Parse it. */
925 GString *portion = context->leftover_char_portion;
927 g_string_append_len (context->leftover_char_portion,
928 text, first_char - text);
930 /* hacks to allow recursion */
931 context->parsing = FALSE;
932 context->leftover_char_portion = NULL;
934 if (!g_markup_parse_context_parse (context,
935 portion->str, portion->len,
938 g_assert (context->state == STATE_ERROR);
941 g_string_free (portion, TRUE);
942 context->parsing = TRUE;
944 /* Skip the fraction of char that was in this text */
945 text_len -= (first_char - text);
950 /* another little chunk of the leftover char; geez
951 * someone is inefficient.
953 g_string_append_len (context->leftover_char_portion,
956 if (context->leftover_char_portion->len > 7)
958 /* The leftover char portion is too big to be
963 G_MARKUP_ERROR_BAD_UTF8,
964 _("Invalid UTF-8 encoded text"));
971 context->current_text = text;
972 context->current_text_len = text_len;
973 context->iter = context->current_text;
974 context->start = context->iter;
976 /* Nothing left after finishing the leftover char, or nothing
977 * passed in to begin with.
979 if (context->current_text_len == 0)
982 /* find_current_text_end () assumes the string starts at
983 * a character start, so we need to validate at least
984 * that much. It doesn't assume any following bytes
987 if ((*context->current_text & 0xc0) == 0x80) /* not a char start */
991 G_MARKUP_ERROR_BAD_UTF8,
992 _("Invalid UTF-8 encoded text"));
996 /* Initialize context->current_text_end, possibly adjusting
997 * current_text_len, and add any leftover char portion
999 find_current_text_end (context);
1001 /* Validate UTF8 (must be done after we find the end, since
1002 * we could have a trailing incomplete char)
1004 if (!g_utf8_validate (context->current_text,
1005 context->current_text_len,
1010 p = context->current_text;
1011 while (p != context->current_text_end)
1018 context->line_number += newlines;
1022 G_MARKUP_ERROR_BAD_UTF8,
1023 _("Invalid UTF-8 encoded text"));
1027 while (context->iter != context->current_text_end)
1029 switch (context->state)
1032 /* Possible next state: AFTER_OPEN_ANGLE */
1034 g_assert (context->tag_stack == NULL);
1036 /* whitespace is ignored outside of any elements */
1037 skip_spaces (context);
1039 if (context->iter != context->current_text_end)
1041 if (*context->iter == '<')
1043 /* Move after the open angle */
1044 advance_char (context);
1046 context->state = STATE_AFTER_OPEN_ANGLE;
1048 /* this could start a passthrough */
1049 context->start = context->iter;
1051 /* document is now non-empty */
1052 context->document_empty = FALSE;
1058 G_MARKUP_ERROR_PARSE,
1059 _("Document must begin with an element (e.g. <book>)"));
1064 case STATE_AFTER_OPEN_ANGLE:
1065 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1066 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1068 if (*context->iter == '?' ||
1069 *context->iter == '!')
1071 /* include < in the passthrough */
1072 const gchar *openangle = "<";
1073 add_to_partial (context, openangle, openangle + 1);
1074 context->start = context->iter;
1075 context->balance = 1;
1076 context->state = STATE_INSIDE_PASSTHROUGH;
1078 else if (*context->iter == '/')
1081 advance_char (context);
1083 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1085 else if (is_name_start_char (context->iter))
1087 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1089 /* start of tag name */
1090 context->start = context->iter;
1098 G_MARKUP_ERROR_PARSE,
1099 _("'%s' is not a valid character following "
1100 "a '<' character; it may not begin an "
1102 utf8_str (context->iter, buf));
1106 /* The AFTER_CLOSE_ANGLE state is actually sort of
1107 * broken, because it doesn't correspond to a range
1108 * of characters in the input stream as the others do,
1109 * and thus makes things harder to conceptualize
1111 case STATE_AFTER_CLOSE_ANGLE:
1112 /* Possible next states: INSIDE_TEXT, STATE_START */
1113 if (context->tag_stack == NULL)
1115 context->start = NULL;
1116 context->state = STATE_START;
1120 context->start = context->iter;
1121 context->state = STATE_INSIDE_TEXT;
1125 case STATE_AFTER_ELISION_SLASH:
1126 /* Possible next state: AFTER_CLOSE_ANGLE */
1129 /* We need to pop the tag stack and call the end_element
1130 * function, since this is the close tag
1132 GError *tmp_error = NULL;
1134 g_assert (context->tag_stack != NULL);
1137 if (context->parser->end_element)
1138 (* context->parser->end_element) (context,
1139 context->tag_stack->data,
1145 mark_error (context, tmp_error);
1146 g_propagate_error (error, tmp_error);
1150 if (*context->iter == '>')
1152 /* move after the close angle */
1153 advance_char (context);
1154 context->state = STATE_AFTER_CLOSE_ANGLE;
1162 G_MARKUP_ERROR_PARSE,
1163 _("Odd character '%s', expected a '>' character "
1164 "to end the start tag of element '%s'"),
1165 utf8_str (context->iter, buf),
1166 current_element (context));
1170 g_free (context->tag_stack->data);
1171 context->tag_stack = g_slist_delete_link (context->tag_stack,
1172 context->tag_stack);
1176 case STATE_INSIDE_OPEN_TAG_NAME:
1177 /* Possible next states: BETWEEN_ATTRIBUTES */
1179 /* if there's a partial chunk then it's the first part of the
1180 * tag name. If there's a context->start then it's the start
1181 * of the tag name in current_text, the partial chunk goes
1182 * before that start though.
1184 advance_to_name_end (context);
1186 if (context->iter == context->current_text_end)
1188 /* The name hasn't necessarily ended. Merge with
1189 * partial chunk, leave state unchanged.
1191 add_to_partial (context, context->start, context->iter);
1195 /* The name has ended. Combine it with the partial chunk
1196 * if any; push it on the stack; enter next state.
1198 add_to_partial (context, context->start, context->iter);
1199 context->tag_stack =
1200 g_slist_prepend (context->tag_stack,
1201 g_string_free (context->partial_chunk,
1204 context->partial_chunk = NULL;
1206 context->state = STATE_BETWEEN_ATTRIBUTES;
1207 context->start = NULL;
1211 case STATE_INSIDE_ATTRIBUTE_NAME:
1212 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1214 advance_to_name_end (context);
1215 add_to_partial (context, context->start, context->iter);
1217 /* read the full name, if we enter the equals sign state
1218 * then add the attribute to the list (without the value),
1219 * otherwise store a partial chunk to be prepended later.
1221 if (context->iter != context->current_text_end)
1222 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1225 case STATE_AFTER_ATTRIBUTE_NAME:
1226 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1228 skip_spaces (context);
1230 if (context->iter != context->current_text_end)
1232 /* The name has ended. Combine it with the partial chunk
1233 * if any; push it on the stack; enter next state.
1235 add_attribute (context, g_string_free (context->partial_chunk, FALSE));
1237 context->partial_chunk = NULL;
1238 context->start = NULL;
1240 if (*context->iter == '=')
1242 advance_char (context);
1243 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1251 G_MARKUP_ERROR_PARSE,
1252 _("Odd character '%s', expected a '=' after "
1253 "attribute name '%s' of element '%s'"),
1254 utf8_str (context->iter, buf),
1255 current_attribute (context),
1256 current_element (context));
1262 case STATE_BETWEEN_ATTRIBUTES:
1263 /* Possible next states: AFTER_CLOSE_ANGLE,
1264 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1266 skip_spaces (context);
1268 if (context->iter != context->current_text_end)
1270 if (*context->iter == '/')
1272 advance_char (context);
1273 context->state = STATE_AFTER_ELISION_SLASH;
1275 else if (*context->iter == '>')
1278 advance_char (context);
1279 context->state = STATE_AFTER_CLOSE_ANGLE;
1281 else if (is_name_start_char (context->iter))
1283 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1284 /* start of attribute name */
1285 context->start = context->iter;
1293 G_MARKUP_ERROR_PARSE,
1294 _("Odd character '%s', expected a '>' or '/' "
1295 "character to end the start tag of "
1296 "element '%s', or optionally an attribute; "
1297 "perhaps you used an invalid character in "
1298 "an attribute name"),
1299 utf8_str (context->iter, buf),
1300 current_element (context));
1303 /* If we're done with attributes, invoke
1304 * the start_element callback
1306 if (context->state == STATE_AFTER_ELISION_SLASH ||
1307 context->state == STATE_AFTER_CLOSE_ANGLE)
1309 const gchar *start_name;
1310 /* Ugly, but the current code expects an empty array instead of NULL */
1311 const gchar *empty = NULL;
1312 const gchar **attr_names = ∅
1313 const gchar **attr_values = ∅
1316 /* Call user callback for element start */
1317 start_name = current_element (context);
1319 if (context->cur_attr >= 0)
1321 attr_names = (const gchar**)context->attr_names;
1322 attr_values = (const gchar**)context->attr_values;
1326 if (context->parser->start_element)
1327 (* context->parser->start_element) (context,
1329 (const gchar **)attr_names,
1330 (const gchar **)attr_values,
1334 /* Go ahead and free the attributes. */
1335 for (; context->cur_attr >= 0; context->cur_attr--)
1337 int pos = context->cur_attr;
1338 g_free (context->attr_names[pos]);
1339 g_free (context->attr_values[pos]);
1340 context->attr_names[pos] = context->attr_values[pos] = NULL;
1342 g_assert (context->cur_attr == -1);
1343 g_assert (context->attr_names == NULL ||
1344 context->attr_names[0] == NULL);
1345 g_assert (context->attr_values == NULL ||
1346 context->attr_values[0] == NULL);
1348 if (tmp_error != NULL)
1350 mark_error (context, tmp_error);
1351 g_propagate_error (error, tmp_error);
1357 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1358 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1360 skip_spaces (context);
1362 if (context->iter != context->current_text_end)
1364 if (*context->iter == '"')
1366 advance_char (context);
1367 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1368 context->start = context->iter;
1370 else if (*context->iter == '\'')
1372 advance_char (context);
1373 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1374 context->start = context->iter;
1382 G_MARKUP_ERROR_PARSE,
1383 _("Odd character '%s', expected an open quote mark "
1384 "after the equals sign when giving value for "
1385 "attribute '%s' of element '%s'"),
1386 utf8_str (context->iter, buf),
1387 current_attribute (context),
1388 current_element (context));
1393 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1394 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1395 /* Possible next states: BETWEEN_ATTRIBUTES */
1399 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1410 if (*context->iter == delim)
1413 while (advance_char (context));
1415 if (context->iter == context->current_text_end)
1417 /* The value hasn't necessarily ended. Merge with
1418 * partial chunk, leave state unchanged.
1420 add_to_partial (context, context->start, context->iter);
1424 /* The value has ended at the quote mark. Combine it
1425 * with the partial chunk if any; set it for the current
1430 add_to_partial (context, context->start, context->iter);
1432 g_assert (context->cur_attr >= 0);
1434 if (unescape_text (context,
1435 context->partial_chunk->str,
1436 context->partial_chunk->str +
1437 context->partial_chunk->len,
1441 /* success, advance past quote and set state. */
1442 context->attr_values[context->cur_attr] = g_string_free (unescaped, FALSE);
1443 advance_char (context);
1444 context->state = STATE_BETWEEN_ATTRIBUTES;
1445 context->start = NULL;
1448 truncate_partial (context);
1452 case STATE_INSIDE_TEXT:
1453 /* Possible next states: AFTER_OPEN_ANGLE */
1456 if (*context->iter == '<')
1459 while (advance_char (context));
1461 /* The text hasn't necessarily ended. Merge with
1462 * partial chunk, leave state unchanged.
1465 add_to_partial (context, context->start, context->iter);
1467 if (context->iter != context->current_text_end)
1469 GString *unescaped = NULL;
1471 /* The text has ended at the open angle. Call the text
1475 if (unescape_text (context,
1476 context->partial_chunk->str,
1477 context->partial_chunk->str +
1478 context->partial_chunk->len,
1482 GError *tmp_error = NULL;
1484 if (context->parser->text)
1485 (*context->parser->text) (context,
1491 g_string_free (unescaped, TRUE);
1493 if (tmp_error == NULL)
1495 /* advance past open angle and set state. */
1496 advance_char (context);
1497 context->state = STATE_AFTER_OPEN_ANGLE;
1498 /* could begin a passthrough */
1499 context->start = context->iter;
1503 mark_error (context, tmp_error);
1504 g_propagate_error (error, tmp_error);
1508 truncate_partial (context);
1512 case STATE_AFTER_CLOSE_TAG_SLASH:
1513 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1514 if (is_name_start_char (context->iter))
1516 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1518 /* start of tag name */
1519 context->start = context->iter;
1527 G_MARKUP_ERROR_PARSE,
1528 _("'%s' is not a valid character following "
1529 "the characters '</'; '%s' may not begin an "
1531 utf8_str (context->iter, buf),
1532 utf8_str (context->iter, buf));
1536 case STATE_INSIDE_CLOSE_TAG_NAME:
1537 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1538 advance_to_name_end (context);
1539 add_to_partial (context, context->start, context->iter);
1541 if (context->iter != context->current_text_end)
1542 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1545 case STATE_AFTER_CLOSE_TAG_NAME:
1546 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1548 skip_spaces (context);
1550 if (context->iter != context->current_text_end)
1554 /* The name has ended. Combine it with the partial chunk
1555 * if any; check that it matches stack top and pop
1556 * stack; invoke proper callback; enter next state.
1558 close_name = g_string_free (context->partial_chunk, FALSE);
1559 context->partial_chunk = NULL;
1561 if (*context->iter != '>')
1567 G_MARKUP_ERROR_PARSE,
1568 _("'%s' is not a valid character following "
1569 "the close element name '%s'; the allowed "
1570 "character is '>'"),
1571 utf8_str (context->iter, buf),
1574 else if (context->tag_stack == NULL)
1578 G_MARKUP_ERROR_PARSE,
1579 _("Element '%s' was closed, no element "
1580 "is currently open"),
1583 else if (strcmp (close_name, current_element (context)) != 0)
1587 G_MARKUP_ERROR_PARSE,
1588 _("Element '%s' was closed, but the currently "
1589 "open element is '%s'"),
1591 current_element (context));
1596 advance_char (context);
1597 context->state = STATE_AFTER_CLOSE_ANGLE;
1598 context->start = NULL;
1600 /* call the end_element callback */
1602 if (context->parser->end_element)
1603 (* context->parser->end_element) (context,
1609 /* Pop the tag stack */
1610 g_free (context->tag_stack->data);
1611 context->tag_stack = g_slist_delete_link (context->tag_stack,
1612 context->tag_stack);
1616 mark_error (context, tmp_error);
1617 g_propagate_error (error, tmp_error);
1621 g_free (close_name);
1625 case STATE_INSIDE_PASSTHROUGH:
1626 /* Possible next state: AFTER_CLOSE_ANGLE */
1629 if (*context->iter == '<')
1631 if (*context->iter == '>')
1634 add_to_partial (context, context->start, context->iter);
1635 context->start = context->iter;
1636 if ((g_str_has_prefix (context->partial_chunk->str, "<?")
1637 && g_str_has_suffix (context->partial_chunk->str, "?")) ||
1638 (g_str_has_prefix (context->partial_chunk->str, "<!--")
1639 && g_str_has_suffix (context->partial_chunk->str, "--")) ||
1640 (g_str_has_prefix (context->partial_chunk->str, "<![CDATA[")
1641 && g_str_has_suffix (context->partial_chunk->str, "]]")) ||
1642 (g_str_has_prefix (context->partial_chunk->str, "<!DOCTYPE")
1643 && context->balance == 0))
1647 while (advance_char (context));
1649 if (context->iter == context->current_text_end)
1651 /* The passthrough hasn't necessarily ended. Merge with
1652 * partial chunk, leave state unchanged.
1654 add_to_partial (context, context->start, context->iter);
1658 /* The passthrough has ended at the close angle. Combine
1659 * it with the partial chunk if any. Call the passthrough
1660 * callback. Note that the open/close angles are
1661 * included in the text of the passthrough.
1663 GError *tmp_error = NULL;
1665 advance_char (context); /* advance past close angle */
1666 add_to_partial (context, context->start, context->iter);
1668 if (context->parser->passthrough)
1669 (*context->parser->passthrough) (context,
1670 context->partial_chunk->str,
1671 context->partial_chunk->len,
1675 truncate_partial (context);
1677 if (tmp_error == NULL)
1679 context->state = STATE_AFTER_CLOSE_ANGLE;
1680 context->start = context->iter; /* could begin text */
1684 mark_error (context, tmp_error);
1685 g_propagate_error (error, tmp_error);
1695 g_assert_not_reached ();
1701 context->parsing = FALSE;
1703 return context->state != STATE_ERROR;
1707 * g_markup_parse_context_end_parse:
1708 * @context: a #GMarkupParseContext
1709 * @error: return location for a #GError
1711 * Signals to the #GMarkupParseContext that all data has been
1712 * fed into the parse context with g_markup_parse_context_parse().
1713 * This function reports an error if the document isn't complete,
1714 * for example if elements are still open.
1716 * Return value: %TRUE on success, %FALSE if an error was set
1719 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1722 g_return_val_if_fail (context != NULL, FALSE);
1723 g_return_val_if_fail (!context->parsing, FALSE);
1724 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1726 if (context->partial_chunk != NULL)
1728 g_string_free (context->partial_chunk, TRUE);
1729 context->partial_chunk = NULL;
1732 if (context->document_empty)
1734 set_error (context, error, G_MARKUP_ERROR_EMPTY,
1735 _("Document was empty or contained only whitespace"));
1739 context->parsing = TRUE;
1741 switch (context->state)
1747 case STATE_AFTER_OPEN_ANGLE:
1748 set_error (context, error, G_MARKUP_ERROR_PARSE,
1749 _("Document ended unexpectedly just after an open angle bracket '<'"));
1752 case STATE_AFTER_CLOSE_ANGLE:
1753 if (context->tag_stack != NULL)
1755 /* Error message the same as for INSIDE_TEXT */
1756 set_error (context, error, G_MARKUP_ERROR_PARSE,
1757 _("Document ended unexpectedly with elements still open - "
1758 "'%s' was the last element opened"),
1759 current_element (context));
1763 case STATE_AFTER_ELISION_SLASH:
1764 set_error (context, error, G_MARKUP_ERROR_PARSE,
1765 _("Document ended unexpectedly, expected to see a close angle "
1766 "bracket ending the tag <%s/>"), current_element (context));
1769 case STATE_INSIDE_OPEN_TAG_NAME:
1770 set_error (context, error, G_MARKUP_ERROR_PARSE,
1771 _("Document ended unexpectedly inside an element name"));
1774 case STATE_INSIDE_ATTRIBUTE_NAME:
1775 set_error (context, error, G_MARKUP_ERROR_PARSE,
1776 _("Document ended unexpectedly inside an attribute name"));
1779 case STATE_BETWEEN_ATTRIBUTES:
1780 set_error (context, error, G_MARKUP_ERROR_PARSE,
1781 _("Document ended unexpectedly inside an element-opening "
1785 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1786 set_error (context, error, G_MARKUP_ERROR_PARSE,
1787 _("Document ended unexpectedly after the equals sign "
1788 "following an attribute name; no attribute value"));
1791 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1792 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1793 set_error (context, error, G_MARKUP_ERROR_PARSE,
1794 _("Document ended unexpectedly while inside an attribute "
1798 case STATE_INSIDE_TEXT:
1799 g_assert (context->tag_stack != NULL);
1800 set_error (context, error, G_MARKUP_ERROR_PARSE,
1801 _("Document ended unexpectedly with elements still open - "
1802 "'%s' was the last element opened"),
1803 current_element (context));
1806 case STATE_AFTER_CLOSE_TAG_SLASH:
1807 case STATE_INSIDE_CLOSE_TAG_NAME:
1808 set_error (context, error, G_MARKUP_ERROR_PARSE,
1809 _("Document ended unexpectedly inside the close tag for "
1810 "element '%s'"), current_element (context));
1813 case STATE_INSIDE_PASSTHROUGH:
1814 set_error (context, error, G_MARKUP_ERROR_PARSE,
1815 _("Document ended unexpectedly inside a comment or "
1816 "processing instruction"));
1821 g_assert_not_reached ();
1825 context->parsing = FALSE;
1827 return context->state != STATE_ERROR;
1831 * g_markup_parse_context_get_element:
1832 * @context: a #GMarkupParseContext
1833 * @returns: the name of the currently open element, or %NULL
1835 * Retrieves the name of the currently open element.
1839 G_CONST_RETURN gchar *
1840 g_markup_parse_context_get_element (GMarkupParseContext *context)
1842 g_return_val_if_fail (context != NULL, NULL);
1844 if (context->tag_stack == NULL)
1847 return current_element (context);
1851 * g_markup_parse_context_get_position:
1852 * @context: a #GMarkupParseContext
1853 * @line_number: return location for a line number, or %NULL
1854 * @char_number: return location for a char-on-line number, or %NULL
1856 * Retrieves the current line number and the number of the character on
1857 * that line. Intended for use in error messages; there are no strict
1858 * semantics for what constitutes the "current" line number other than
1859 * "the best number we could come up with for error messages."
1863 g_markup_parse_context_get_position (GMarkupParseContext *context,
1867 g_return_if_fail (context != NULL);
1870 *line_number = context->line_number;
1873 *char_number = context->char_number;
1877 append_escaped_text (GString *str,
1885 end = text + length;
1890 next = g_utf8_next_char (p);
1895 g_string_append (str, "&");
1899 g_string_append (str, "<");
1903 g_string_append (str, ">");
1907 g_string_append (str, "'");
1911 g_string_append (str, """);
1915 g_string_append_len (str, p, next - p);
1924 * g_markup_escape_text:
1925 * @text: some valid UTF-8 text
1926 * @length: length of @text in bytes
1928 * Escapes text so that the markup parser will parse it verbatim.
1929 * Less than, greater than, ampersand, etc. are replaced with the
1930 * corresponding entities. This function would typically be used
1931 * when writing out a file to be parsed with the markup parser.
1933 * Note that this function doesn't protect whitespace and line endings
1934 * from being processed according to the XML rules for normalization
1935 * of line endings and attribute values.
1937 * Return value: escaped text
1940 g_markup_escape_text (const gchar *text,
1945 g_return_val_if_fail (text != NULL, NULL);
1948 length = strlen (text);
1950 /* prealloc at least as long as original text */
1951 str = g_string_sized_new (length);
1952 append_escaped_text (str, text, length);
1954 return g_string_free (str, FALSE);
1959 * @format: a printf-style format string
1960 * @after: location to store a pointer to the character after
1961 * the returned conversion. On a %NULL return, returns the
1962 * pointer to the trailing NUL in the string
1964 * Find the next conversion in a printf-style format string.
1965 * Partially based on code from printf-parser.c,
1966 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
1968 * Return value: pointer to the next conversion in @format,
1969 * or %NULL, if none.
1972 find_conversion (const char *format,
1975 const char *start = format;
1978 while (*start != '\0' && *start != '%')
1995 /* Test for positional argument. */
1996 if (*cp >= '0' && *cp <= '9')
2000 for (np = cp; *np >= '0' && *np <= '9'; np++)
2006 /* Skip the flags. */
2020 /* Skip the field width. */
2025 /* Test for positional argument. */
2026 if (*cp >= '0' && *cp <= '9')
2030 for (np = cp; *np >= '0' && *np <= '9'; np++)
2038 for (; *cp >= '0' && *cp <= '9'; cp++)
2042 /* Skip the precision. */
2048 /* Test for positional argument. */
2049 if (*cp >= '0' && *cp <= '9')
2053 for (np = cp; *np >= '0' && *np <= '9'; np++)
2061 for (; *cp >= '0' && *cp <= '9'; cp++)
2066 /* Skip argument type/size specifiers. */
2067 while (*cp == 'h' ||
2076 /* Skip the conversion character. */
2084 * g_markup_vprintf_escaped:
2085 * @format: printf() style format string
2086 * @args: variable argument list, similar to vprintf()
2088 * Formats the data in @args according to @format, escaping
2089 * all string and character arguments in the fashion
2090 * of g_markup_escape_text(). See g_markup_printf_escaped().
2092 * Return value: newly allocated result from formatting
2093 * operation. Free with g_free().
2098 g_markup_vprintf_escaped (const char *format,
2103 GString *result = NULL;
2104 gchar *output1 = NULL;
2105 gchar *output2 = NULL;
2106 const char *p, *op1, *op2;
2109 /* The technique here, is that we make two format strings that
2110 * have the identical conversions in the identical order to the
2111 * original strings, but differ in the text in-between. We
2112 * then use the normal g_strdup_vprintf() to format the arguments
2113 * with the two new format strings. By comparing the results,
2114 * we can figure out what segments of the output come from
2115 * the the original format string, and what from the arguments,
2116 * and thus know what portions of the string to escape.
2118 * For instance, for:
2120 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2122 * We form the two format strings "%sX%dX" and %sY%sY". The results
2123 * of formatting with those two strings are
2125 * "%sX%dX" => "Susan & FredX5X"
2126 * "%sY%dY" => "Susan & FredY5Y"
2128 * To find the span of the first argument, we find the first position
2129 * where the two arguments differ, which tells us that the first
2130 * argument formatted to "Susan & Fred". We then escape that
2131 * to "Susan & Fred" and join up with the intermediate portions
2132 * of the format string and the second argument to get
2133 * "Susan & Fred ate 5 apples".
2136 /* Create the two modified format strings
2138 format1 = g_string_new (NULL);
2139 format2 = g_string_new (NULL);
2144 const char *conv = find_conversion (p, &after);
2148 g_string_append_len (format1, conv, after - conv);
2149 g_string_append_c (format1, 'X');
2150 g_string_append_len (format2, conv, after - conv);
2151 g_string_append_c (format2, 'Y');
2156 /* Use them to format the arguments
2158 G_VA_COPY (args2, args);
2160 output1 = g_strdup_vprintf (format1->str, args);
2165 output2 = g_strdup_vprintf (format2->str, args2);
2170 result = g_string_new (NULL);
2172 /* Iterate through the original format string again,
2173 * copying the non-conversion portions and the escaped
2174 * converted arguments to the output string.
2182 const char *output_start;
2183 const char *conv = find_conversion (p, &after);
2186 if (!conv) /* The end, after points to the trailing \0 */
2188 g_string_append_len (result, p, after - p);
2192 g_string_append_len (result, p, conv - p);
2194 while (*op1 == *op2)
2200 escaped = g_markup_escape_text (output_start, op1 - output_start);
2201 g_string_append (result, escaped);
2210 g_string_free (format1, TRUE);
2211 g_string_free (format2, TRUE);
2216 return g_string_free (result, FALSE);
2222 * g_markup_printf_escaped:
2223 * @format: printf() style format string
2224 * @Varargs: the arguments to insert in the format string
2226 * Formats arguments according to @format, escaping
2227 * all string and character arguments in the fashion
2228 * of g_markup_escape_text(). This is useful when you
2229 * want to insert literal strings into XML-style markup
2230 * output, without having to worry that the strings
2231 * might themselves contain markup.
2233 * <informalexample><programlisting>
2234 * const char *store = "Fortnum & Mason";
2235 * const char *item = "Tea";
2238 * output = g_markup_printf_escaped ("<purchase>"
2239 * "<store>%s</store>"
2240 * "<item>%s</item>"
2241 * "</purchase>",
2243 * </programlisting></informalexample>
2245 * Return value: newly allocated result from formatting
2246 * operation. Free with g_free().
2251 g_markup_printf_escaped (const char *format, ...)
2256 va_start (args, format);
2257 result = g_markup_vprintf_escaped (format, args);
2263 #define __G_MARKUP_C__
2264 #include "galiasdef.c"