Remove trailing space from some translated strings
[glib.git] / glib / gmarkup.c
blobf424026a92dfc3e51e1d5a6d0d0c6693929e0b5e
1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
4 * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
6 * GLib is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * GLib is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with GLib; see the file COPYING.LIB. If not,
18 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
22 #include "config.h"
24 #include <stdarg.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
30 #include "gmarkup.h"
32 #include "gslice.h"
33 #include "galloca.h"
34 #include "gstrfuncs.h"
35 #include "gstring.h"
36 #include "gtestutils.h"
37 #include "glibintl.h"
38 #include "gthread.h"
40 /**
41 * SECTION:markup
42 * @Title: Simple XML Subset Parser
43 * @Short_description: parses a subset of XML
44 * @See_also: <ulink url="http://www.w3.org/TR/REC-xml/">XML
45 * Specification</ulink>
47 * The "GMarkup" parser is intended to parse a simple markup format
48 * that's a subset of XML. This is a small, efficient, easy-to-use
49 * parser. It should not be used if you expect to interoperate with
50 * other applications generating full-scale XML. However, it's very
51 * useful for application data files, config files, etc. where you
52 * know your application will be the only one writing the file.
53 * Full-scale XML parsers should be able to parse the subset used by
54 * GMarkup, so you can easily migrate to full-scale XML at a later
55 * time if the need arises.
57 * GMarkup is not guaranteed to signal an error on all invalid XML;
58 * the parser may accept documents that an XML parser would not.
59 * However, XML documents which are not well-formed<footnote
60 * id="wellformed">Being wellformed is a weaker condition than being
61 * valid. See the <ulink url="http://www.w3.org/TR/REC-xml/">XML
62 * specification</ulink> for definitions of these terms.</footnote>
63 * are not considered valid GMarkup documents.
65 * Simplifications to XML include:
66 * <itemizedlist>
67 * <listitem>Only UTF-8 encoding is allowed</listitem>
68 * <listitem>No user-defined entities</listitem>
69 * <listitem>Processing instructions, comments and the doctype declaration
70 * are "passed through" but are not interpreted in any way</listitem>
71 * <listitem>No DTD or validation.</listitem>
72 * </itemizedlist>
74 * The markup format does support:
75 * <itemizedlist>
76 * <listitem>Elements</listitem>
77 * <listitem>Attributes</listitem>
78 * <listitem>5 standard entities:
79 * <literal>&amp;amp; &amp;lt; &amp;gt; &amp;quot; &amp;apos;</literal>
80 * </listitem>
81 * <listitem>Character references</listitem>
82 * <listitem>Sections marked as CDATA</listitem>
83 * </itemizedlist>
86 G_DEFINE_QUARK (g-markup-error-quark, g_markup_error)
88 typedef enum
90 STATE_START,
91 STATE_AFTER_OPEN_ANGLE,
92 STATE_AFTER_CLOSE_ANGLE,
93 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
94 STATE_INSIDE_OPEN_TAG_NAME,
95 STATE_INSIDE_ATTRIBUTE_NAME,
96 STATE_AFTER_ATTRIBUTE_NAME,
97 STATE_BETWEEN_ATTRIBUTES,
98 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
99 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
100 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
101 STATE_INSIDE_TEXT,
102 STATE_AFTER_CLOSE_TAG_SLASH,
103 STATE_INSIDE_CLOSE_TAG_NAME,
104 STATE_AFTER_CLOSE_TAG_NAME,
105 STATE_INSIDE_PASSTHROUGH,
106 STATE_ERROR
107 } GMarkupParseState;
109 typedef struct
111 const char *prev_element;
112 const GMarkupParser *prev_parser;
113 gpointer prev_user_data;
114 } GMarkupRecursionTracker;
116 struct _GMarkupParseContext
118 const GMarkupParser *parser;
120 GMarkupParseFlags flags;
122 gint line_number;
123 gint char_number;
125 GMarkupParseState state;
127 gpointer user_data;
128 GDestroyNotify dnotify;
130 /* A piece of character data or an element that
131 * hasn't "ended" yet so we haven't yet called
132 * the callback for it.
134 GString *partial_chunk;
135 GSList *spare_chunks;
137 GSList *tag_stack;
138 GSList *tag_stack_gstr;
139 GSList *spare_list_nodes;
141 GString **attr_names;
142 GString **attr_values;
143 gint cur_attr;
144 gint alloc_attrs;
146 const gchar *current_text;
147 gssize current_text_len;
148 const gchar *current_text_end;
150 /* used to save the start of the last interesting thingy */
151 const gchar *start;
153 const gchar *iter;
155 guint document_empty : 1;
156 guint parsing : 1;
157 guint awaiting_pop : 1;
158 gint balance;
160 /* subparser support */
161 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
162 const char *subparser_element;
163 gpointer held_user_data;
167 * Helpers to reduce our allocation overhead, we have
168 * a well defined allocation lifecycle.
170 static GSList *
171 get_list_node (GMarkupParseContext *context, gpointer data)
173 GSList *node;
174 if (context->spare_list_nodes != NULL)
176 node = context->spare_list_nodes;
177 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
179 else
180 node = g_slist_alloc();
181 node->data = data;
182 return node;
185 static void
186 free_list_node (GMarkupParseContext *context, GSList *node)
188 node->data = NULL;
189 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
192 static inline void
193 string_blank (GString *string)
195 string->str[0] = '\0';
196 string->len = 0;
200 * g_markup_parse_context_new:
201 * @parser: a #GMarkupParser
202 * @flags: one or more #GMarkupParseFlags
203 * @user_data: user data to pass to #GMarkupParser functions
204 * @user_data_dnotify: user data destroy notifier called when
205 * the parse context is freed
207 * Creates a new parse context. A parse context is used to parse
208 * marked-up documents. You can feed any number of documents into
209 * a context, as long as no errors occur; once an error occurs,
210 * the parse context can't continue to parse text (you have to
211 * free it and create a new parse context).
213 * Return value: a new #GMarkupParseContext
215 GMarkupParseContext *
216 g_markup_parse_context_new (const GMarkupParser *parser,
217 GMarkupParseFlags flags,
218 gpointer user_data,
219 GDestroyNotify user_data_dnotify)
221 GMarkupParseContext *context;
223 g_return_val_if_fail (parser != NULL, NULL);
225 context = g_new (GMarkupParseContext, 1);
227 context->parser = parser;
228 context->flags = flags;
229 context->user_data = user_data;
230 context->dnotify = user_data_dnotify;
232 context->line_number = 1;
233 context->char_number = 1;
235 context->partial_chunk = NULL;
236 context->spare_chunks = NULL;
237 context->spare_list_nodes = NULL;
239 context->state = STATE_START;
240 context->tag_stack = NULL;
241 context->tag_stack_gstr = NULL;
242 context->attr_names = NULL;
243 context->attr_values = NULL;
244 context->cur_attr = -1;
245 context->alloc_attrs = 0;
247 context->current_text = NULL;
248 context->current_text_len = -1;
249 context->current_text_end = NULL;
251 context->start = NULL;
252 context->iter = NULL;
254 context->document_empty = TRUE;
255 context->parsing = FALSE;
257 context->awaiting_pop = FALSE;
258 context->subparser_stack = NULL;
259 context->subparser_element = NULL;
261 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
262 context->held_user_data = NULL;
264 context->balance = 0;
266 return context;
269 static void
270 string_full_free (gpointer ptr)
272 g_string_free (ptr, TRUE);
275 static void clear_attributes (GMarkupParseContext *context);
278 * g_markup_parse_context_free:
279 * @context: a #GMarkupParseContext
281 * Frees a #GMarkupParseContext.
283 * This function can't be called from inside one of the
284 * #GMarkupParser functions or while a subparser is pushed.
286 void
287 g_markup_parse_context_free (GMarkupParseContext *context)
289 g_return_if_fail (context != NULL);
290 g_return_if_fail (!context->parsing);
291 g_return_if_fail (!context->subparser_stack);
292 g_return_if_fail (!context->awaiting_pop);
294 if (context->dnotify)
295 (* context->dnotify) (context->user_data);
297 clear_attributes (context);
298 g_free (context->attr_names);
299 g_free (context->attr_values);
301 g_slist_free_full (context->tag_stack_gstr, string_full_free);
302 g_slist_free (context->tag_stack);
304 g_slist_free_full (context->spare_chunks, string_full_free);
305 g_slist_free (context->spare_list_nodes);
307 if (context->partial_chunk)
308 g_string_free (context->partial_chunk, TRUE);
310 g_free (context);
313 static void pop_subparser_stack (GMarkupParseContext *context);
315 static void
316 mark_error (GMarkupParseContext *context,
317 GError *error)
319 context->state = STATE_ERROR;
321 if (context->parser->error)
322 (*context->parser->error) (context, error, context->user_data);
324 /* report the error all the way up to free all the user-data */
325 while (context->subparser_stack)
327 pop_subparser_stack (context);
328 context->awaiting_pop = FALSE; /* already been freed */
330 if (context->parser->error)
331 (*context->parser->error) (context, error, context->user_data);
335 static void
336 set_error (GMarkupParseContext *context,
337 GError **error,
338 GMarkupError code,
339 const gchar *format,
340 ...) G_GNUC_PRINTF (4, 5);
342 static void
343 set_error_literal (GMarkupParseContext *context,
344 GError **error,
345 GMarkupError code,
346 const gchar *message)
348 GError *tmp_error;
350 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
352 g_prefix_error (&tmp_error,
353 _("Error on line %d char %d: "),
354 context->line_number,
355 context->char_number);
357 mark_error (context, tmp_error);
359 g_propagate_error (error, tmp_error);
362 static void
363 set_error (GMarkupParseContext *context,
364 GError **error,
365 GMarkupError code,
366 const gchar *format,
367 ...)
369 gchar *s;
370 gchar *s_valid;
371 va_list args;
373 va_start (args, format);
374 s = g_strdup_vprintf (format, args);
375 va_end (args);
377 /* Make sure that the GError message is valid UTF-8
378 * even if it is complaining about invalid UTF-8 in the markup
380 s_valid = _g_utf8_make_valid (s);
381 set_error_literal (context, error, code, s);
383 g_free (s);
384 g_free (s_valid);
387 static void
388 propagate_error (GMarkupParseContext *context,
389 GError **dest,
390 GError *src)
392 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
393 g_prefix_error (&src,
394 _("Error on line %d char %d: "),
395 context->line_number,
396 context->char_number);
398 mark_error (context, src);
400 g_propagate_error (dest, src);
403 #define IS_COMMON_NAME_END_CHAR(c) \
404 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
406 static gboolean
407 slow_name_validate (GMarkupParseContext *context,
408 const gchar *name,
409 GError **error)
411 const gchar *p = name;
413 if (!g_utf8_validate (name, strlen (name), NULL))
415 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
416 _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
417 return FALSE;
420 if (!(g_ascii_isalpha (*p) ||
421 (!IS_COMMON_NAME_END_CHAR (*p) &&
422 (*p == '_' ||
423 *p == ':' ||
424 g_unichar_isalpha (g_utf8_get_char (p))))))
426 set_error (context, error, G_MARKUP_ERROR_PARSE,
427 _("'%s' is not a valid name"), name);
428 return FALSE;
431 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
433 /* is_name_char */
434 if (!(g_ascii_isalnum (*p) ||
435 (!IS_COMMON_NAME_END_CHAR (*p) &&
436 (*p == '.' ||
437 *p == '-' ||
438 *p == '_' ||
439 *p == ':' ||
440 g_unichar_isalpha (g_utf8_get_char (p))))))
442 set_error (context, error, G_MARKUP_ERROR_PARSE,
443 _("'%s' is not a valid name: '%c'"), name, *p);
444 return FALSE;
447 return TRUE;
451 * Use me for elements, attributes etc.
453 static gboolean
454 name_validate (GMarkupParseContext *context,
455 const gchar *name,
456 GError **error)
458 char mask;
459 const char *p;
461 /* name start char */
462 p = name;
463 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
464 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
465 goto slow_validate;
467 for (mask = *p++; *p != '\0'; p++)
469 mask |= *p;
471 /* is_name_char */
472 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
473 (!IS_COMMON_NAME_END_CHAR (*p) &&
474 (*p == '.' ||
475 *p == '-' ||
476 *p == '_' ||
477 *p == ':')))))
478 goto slow_validate;
481 if (mask & 0x80) /* un-common / non-ascii */
482 goto slow_validate;
484 return TRUE;
486 slow_validate:
487 return slow_name_validate (context, name, error);
490 static gboolean
491 text_validate (GMarkupParseContext *context,
492 const gchar *p,
493 gint len,
494 GError **error)
496 if (!g_utf8_validate (p, len, NULL))
498 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
499 _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
500 return FALSE;
502 else
503 return TRUE;
506 static gchar*
507 char_str (gunichar c,
508 gchar *buf)
510 memset (buf, 0, 8);
511 g_unichar_to_utf8 (c, buf);
512 return buf;
515 static gchar*
516 utf8_str (const gchar *utf8,
517 gchar *buf)
519 char_str (g_utf8_get_char (utf8), buf);
520 return buf;
523 static void
524 set_unescape_error (GMarkupParseContext *context,
525 GError **error,
526 const gchar *remaining_text,
527 GMarkupError code,
528 const gchar *format,
529 ...)
531 GError *tmp_error;
532 gchar *s;
533 va_list args;
534 gint remaining_newlines;
535 const gchar *p;
537 remaining_newlines = 0;
538 p = remaining_text;
539 while (*p != '\0')
541 if (*p == '\n')
542 ++remaining_newlines;
543 ++p;
546 va_start (args, format);
547 s = g_strdup_vprintf (format, args);
548 va_end (args);
550 tmp_error = g_error_new (G_MARKUP_ERROR,
551 code,
552 _("Error on line %d: %s"),
553 context->line_number - remaining_newlines,
556 g_free (s);
558 mark_error (context, tmp_error);
560 g_propagate_error (error, tmp_error);
564 * re-write the GString in-place, unescaping anything that escaped.
565 * most XML does not contain entities, or escaping.
567 static gboolean
568 unescape_gstring_inplace (GMarkupParseContext *context,
569 GString *string,
570 gboolean *is_ascii,
571 GError **error)
573 char mask, *to;
574 int line_num = 1;
575 const char *from;
576 gboolean normalize_attribute;
578 *is_ascii = FALSE;
580 /* are we unescaping an attribute or not ? */
581 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
582 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
583 normalize_attribute = TRUE;
584 else
585 normalize_attribute = FALSE;
588 * Meeks' theorum: unescaping can only shrink text.
589 * for &lt; etc. this is obvious, for &#xffff; more
590 * thought is required, but this is patently so.
592 mask = 0;
593 for (from = to = string->str; *from != '\0'; from++, to++)
595 *to = *from;
597 mask |= *to;
598 if (*to == '\n')
599 line_num++;
600 if (normalize_attribute && (*to == '\t' || *to == '\n'))
601 *to = ' ';
602 if (*to == '\r')
604 *to = normalize_attribute ? ' ' : '\n';
605 if (from[1] == '\n')
606 from++;
608 if (*from == '&')
610 from++;
611 if (*from == '#')
613 gboolean is_hex = FALSE;
614 gulong l;
615 gchar *end = NULL;
617 from++;
619 if (*from == 'x')
621 is_hex = TRUE;
622 from++;
625 /* digit is between start and p */
626 errno = 0;
627 if (is_hex)
628 l = strtoul (from, &end, 16);
629 else
630 l = strtoul (from, &end, 10);
632 if (end == from || errno != 0)
634 set_unescape_error (context, error,
635 from, G_MARKUP_ERROR_PARSE,
636 _("Failed to parse '%-.*s', which "
637 "should have been a digit "
638 "inside a character reference "
639 "(&#234; for example) - perhaps "
640 "the digit is too large"),
641 end - from, from);
642 return FALSE;
644 else if (*end != ';')
646 set_unescape_error (context, error,
647 from, G_MARKUP_ERROR_PARSE,
648 _("Character reference did not end with a "
649 "semicolon; "
650 "most likely you used an ampersand "
651 "character without intending to start "
652 "an entity - escape ampersand as &amp;"));
653 return FALSE;
655 else
657 /* characters XML 1.1 permits */
658 if ((0 < l && l <= 0xD7FF) ||
659 (0xE000 <= l && l <= 0xFFFD) ||
660 (0x10000 <= l && l <= 0x10FFFF))
662 gchar buf[8];
663 char_str (l, buf);
664 strcpy (to, buf);
665 to += strlen (buf) - 1;
666 from = end;
667 if (l >= 0x80) /* not ascii */
668 mask |= 0x80;
670 else
672 set_unescape_error (context, error,
673 from, G_MARKUP_ERROR_PARSE,
674 _("Character reference '%-.*s' does not "
675 "encode a permitted character"),
676 end - from, from);
677 return FALSE;
682 else if (strncmp (from, "lt;", 3) == 0)
684 *to = '<';
685 from += 2;
687 else if (strncmp (from, "gt;", 3) == 0)
689 *to = '>';
690 from += 2;
692 else if (strncmp (from, "amp;", 4) == 0)
694 *to = '&';
695 from += 3;
697 else if (strncmp (from, "quot;", 5) == 0)
699 *to = '"';
700 from += 4;
702 else if (strncmp (from, "apos;", 5) == 0)
704 *to = '\'';
705 from += 4;
707 else
709 if (*from == ';')
710 set_unescape_error (context, error,
711 from, G_MARKUP_ERROR_PARSE,
712 _("Empty entity '&;' seen; valid "
713 "entities are: &amp; &quot; &lt; &gt; &apos;"));
714 else
716 const char *end = strchr (from, ';');
717 if (end)
718 set_unescape_error (context, error,
719 from, G_MARKUP_ERROR_PARSE,
720 _("Entity name '%-.*s' is not known"),
721 end-from, from);
722 else
723 set_unescape_error (context, error,
724 from, G_MARKUP_ERROR_PARSE,
725 _("Entity did not end with a semicolon; "
726 "most likely you used an ampersand "
727 "character without intending to start "
728 "an entity - escape ampersand as &amp;"));
730 return FALSE;
735 g_assert (to - string->str <= string->len);
736 if (to - string->str != string->len)
737 g_string_truncate (string, to - string->str);
739 *is_ascii = !(mask & 0x80);
741 return TRUE;
744 static inline gboolean
745 advance_char (GMarkupParseContext *context)
747 context->iter++;
748 context->char_number++;
750 if (G_UNLIKELY (context->iter == context->current_text_end))
751 return FALSE;
753 else if (G_UNLIKELY (*context->iter == '\n'))
755 context->line_number++;
756 context->char_number = 1;
759 return TRUE;
762 static inline gboolean
763 xml_isspace (char c)
765 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
768 static void
769 skip_spaces (GMarkupParseContext *context)
773 if (!xml_isspace (*context->iter))
774 return;
776 while (advance_char (context));
779 static void
780 advance_to_name_end (GMarkupParseContext *context)
784 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
785 return;
786 if (xml_isspace (*(context->iter)))
787 return;
789 while (advance_char (context));
792 static void
793 release_chunk (GMarkupParseContext *context, GString *str)
795 GSList *node;
796 if (!str)
797 return;
798 if (str->allocated_len > 256)
799 { /* large strings are unusual and worth freeing */
800 g_string_free (str, TRUE);
801 return;
803 string_blank (str);
804 node = get_list_node (context, str);
805 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
808 static void
809 add_to_partial (GMarkupParseContext *context,
810 const gchar *text_start,
811 const gchar *text_end)
813 if (context->partial_chunk == NULL)
814 { /* allocate a new chunk to parse into */
816 if (context->spare_chunks != NULL)
818 GSList *node = context->spare_chunks;
819 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
820 context->partial_chunk = node->data;
821 free_list_node (context, node);
823 else
824 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
827 if (text_start != text_end)
828 g_string_insert_len (context->partial_chunk, -1,
829 text_start, text_end - text_start);
832 static inline void
833 truncate_partial (GMarkupParseContext *context)
835 if (context->partial_chunk != NULL)
836 string_blank (context->partial_chunk);
839 static inline const gchar*
840 current_element (GMarkupParseContext *context)
842 return context->tag_stack->data;
845 static void
846 pop_subparser_stack (GMarkupParseContext *context)
848 GMarkupRecursionTracker *tracker;
850 g_assert (context->subparser_stack);
852 tracker = context->subparser_stack->data;
854 context->awaiting_pop = TRUE;
855 context->held_user_data = context->user_data;
857 context->user_data = tracker->prev_user_data;
858 context->parser = tracker->prev_parser;
859 context->subparser_element = tracker->prev_element;
860 g_slice_free (GMarkupRecursionTracker, tracker);
862 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
863 context->subparser_stack);
866 static void
867 push_partial_as_tag (GMarkupParseContext *context)
869 GString *str = context->partial_chunk;
870 /* sadly, this is exported by gmarkup_get_element_stack as-is */
871 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
872 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
873 context->partial_chunk = NULL;
876 static void
877 pop_tag (GMarkupParseContext *context)
879 GSList *nodea, *nodeb;
881 nodea = context->tag_stack;
882 nodeb = context->tag_stack_gstr;
883 release_chunk (context, nodeb->data);
884 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
885 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
886 free_list_node (context, nodea);
887 free_list_node (context, nodeb);
890 static void
891 possibly_finish_subparser (GMarkupParseContext *context)
893 if (current_element (context) == context->subparser_element)
894 pop_subparser_stack (context);
897 static void
898 ensure_no_outstanding_subparser (GMarkupParseContext *context)
900 if (context->awaiting_pop)
901 g_critical ("During the first end_element call after invoking a "
902 "subparser you must pop the subparser stack and handle "
903 "the freeing of the subparser user_data. This can be "
904 "done by calling the end function of the subparser. "
905 "Very probably, your program just leaked memory.");
907 /* let valgrind watch the pointer disappear... */
908 context->held_user_data = NULL;
909 context->awaiting_pop = FALSE;
912 static const gchar*
913 current_attribute (GMarkupParseContext *context)
915 g_assert (context->cur_attr >= 0);
916 return context->attr_names[context->cur_attr]->str;
919 static void
920 add_attribute (GMarkupParseContext *context, GString *str)
922 if (context->cur_attr + 2 >= context->alloc_attrs)
924 context->alloc_attrs += 5; /* silly magic number */
925 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
926 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
928 context->cur_attr++;
929 context->attr_names[context->cur_attr] = str;
930 context->attr_values[context->cur_attr] = NULL;
931 context->attr_names[context->cur_attr+1] = NULL;
932 context->attr_values[context->cur_attr+1] = NULL;
935 static void
936 clear_attributes (GMarkupParseContext *context)
938 /* Go ahead and free the attributes. */
939 for (; context->cur_attr >= 0; context->cur_attr--)
941 int pos = context->cur_attr;
942 release_chunk (context, context->attr_names[pos]);
943 release_chunk (context, context->attr_values[pos]);
944 context->attr_names[pos] = context->attr_values[pos] = NULL;
946 g_assert (context->cur_attr == -1);
947 g_assert (context->attr_names == NULL ||
948 context->attr_names[0] == NULL);
949 g_assert (context->attr_values == NULL ||
950 context->attr_values[0] == NULL);
953 /* This has to be a separate function to ensure the alloca's
954 * are unwound on exit - otherwise we grow & blow the stack
955 * with large documents
957 static inline void
958 emit_start_element (GMarkupParseContext *context,
959 GError **error)
961 int i;
962 const gchar *start_name;
963 const gchar **attr_names;
964 const gchar **attr_values;
965 GError *tmp_error;
967 attr_names = g_newa (const gchar *, context->cur_attr + 2);
968 attr_values = g_newa (const gchar *, context->cur_attr + 2);
969 for (i = 0; i < context->cur_attr + 1; i++)
971 attr_names[i] = context->attr_names[i]->str;
972 attr_values[i] = context->attr_values[i]->str;
974 attr_names[i] = NULL;
975 attr_values[i] = NULL;
977 /* Call user callback for element start */
978 tmp_error = NULL;
979 start_name = current_element (context);
981 if (context->parser->start_element &&
982 name_validate (context, start_name, error))
983 (* context->parser->start_element) (context,
984 start_name,
985 (const gchar **)attr_names,
986 (const gchar **)attr_values,
987 context->user_data,
988 &tmp_error);
989 clear_attributes (context);
991 if (tmp_error != NULL)
992 propagate_error (context, error, tmp_error);
996 * g_markup_parse_context_parse:
997 * @context: a #GMarkupParseContext
998 * @text: chunk of text to parse
999 * @text_len: length of @text in bytes
1000 * @error: return location for a #GError
1002 * Feed some data to the #GMarkupParseContext.
1004 * The data need not be valid UTF-8; an error will be signaled if
1005 * it's invalid. The data need not be an entire document; you can
1006 * feed a document into the parser incrementally, via multiple calls
1007 * to this function. Typically, as you receive data from a network
1008 * connection or file, you feed each received chunk of data into this
1009 * function, aborting the process if an error occurs. Once an error
1010 * is reported, no further data may be fed to the #GMarkupParseContext;
1011 * all errors are fatal.
1013 * Return value: %FALSE if an error occurred, %TRUE on success
1015 gboolean
1016 g_markup_parse_context_parse (GMarkupParseContext *context,
1017 const gchar *text,
1018 gssize text_len,
1019 GError **error)
1021 g_return_val_if_fail (context != NULL, FALSE);
1022 g_return_val_if_fail (text != NULL, FALSE);
1023 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1024 g_return_val_if_fail (!context->parsing, FALSE);
1026 if (text_len < 0)
1027 text_len = strlen (text);
1029 if (text_len == 0)
1030 return TRUE;
1032 context->parsing = TRUE;
1035 context->current_text = text;
1036 context->current_text_len = text_len;
1037 context->current_text_end = context->current_text + text_len;
1038 context->iter = context->current_text;
1039 context->start = context->iter;
1041 while (context->iter != context->current_text_end)
1043 switch (context->state)
1045 case STATE_START:
1046 /* Possible next state: AFTER_OPEN_ANGLE */
1048 g_assert (context->tag_stack == NULL);
1050 /* whitespace is ignored outside of any elements */
1051 skip_spaces (context);
1053 if (context->iter != context->current_text_end)
1055 if (*context->iter == '<')
1057 /* Move after the open angle */
1058 advance_char (context);
1060 context->state = STATE_AFTER_OPEN_ANGLE;
1062 /* this could start a passthrough */
1063 context->start = context->iter;
1065 /* document is now non-empty */
1066 context->document_empty = FALSE;
1068 else
1070 set_error_literal (context,
1071 error,
1072 G_MARKUP_ERROR_PARSE,
1073 _("Document must begin with an element (e.g. <book>)"));
1076 break;
1078 case STATE_AFTER_OPEN_ANGLE:
1079 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1080 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1082 if (*context->iter == '?' ||
1083 *context->iter == '!')
1085 /* include < in the passthrough */
1086 const gchar *openangle = "<";
1087 add_to_partial (context, openangle, openangle + 1);
1088 context->start = context->iter;
1089 context->balance = 1;
1090 context->state = STATE_INSIDE_PASSTHROUGH;
1092 else if (*context->iter == '/')
1094 /* move after it */
1095 advance_char (context);
1097 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1099 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1101 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1103 /* start of tag name */
1104 context->start = context->iter;
1106 else
1108 gchar buf[8];
1110 set_error (context,
1111 error,
1112 G_MARKUP_ERROR_PARSE,
1113 _("'%s' is not a valid character following "
1114 "a '<' character; it may not begin an "
1115 "element name"),
1116 utf8_str (context->iter, buf));
1118 break;
1120 /* The AFTER_CLOSE_ANGLE state is actually sort of
1121 * broken, because it doesn't correspond to a range
1122 * of characters in the input stream as the others do,
1123 * and thus makes things harder to conceptualize
1125 case STATE_AFTER_CLOSE_ANGLE:
1126 /* Possible next states: INSIDE_TEXT, STATE_START */
1127 if (context->tag_stack == NULL)
1129 context->start = NULL;
1130 context->state = STATE_START;
1132 else
1134 context->start = context->iter;
1135 context->state = STATE_INSIDE_TEXT;
1137 break;
1139 case STATE_AFTER_ELISION_SLASH:
1140 /* Possible next state: AFTER_CLOSE_ANGLE */
1143 /* We need to pop the tag stack and call the end_element
1144 * function, since this is the close tag
1146 GError *tmp_error = NULL;
1148 g_assert (context->tag_stack != NULL);
1150 possibly_finish_subparser (context);
1152 tmp_error = NULL;
1153 if (context->parser->end_element)
1154 (* context->parser->end_element) (context,
1155 current_element (context),
1156 context->user_data,
1157 &tmp_error);
1159 ensure_no_outstanding_subparser (context);
1161 if (tmp_error)
1163 mark_error (context, tmp_error);
1164 g_propagate_error (error, tmp_error);
1166 else
1168 if (*context->iter == '>')
1170 /* move after the close angle */
1171 advance_char (context);
1172 context->state = STATE_AFTER_CLOSE_ANGLE;
1174 else
1176 gchar buf[8];
1178 set_error (context,
1179 error,
1180 G_MARKUP_ERROR_PARSE,
1181 _("Odd character '%s', expected a '>' character "
1182 "to end the empty-element tag '%s'"),
1183 utf8_str (context->iter, buf),
1184 current_element (context));
1187 pop_tag (context);
1189 break;
1191 case STATE_INSIDE_OPEN_TAG_NAME:
1192 /* Possible next states: BETWEEN_ATTRIBUTES */
1194 /* if there's a partial chunk then it's the first part of the
1195 * tag name. If there's a context->start then it's the start
1196 * of the tag name in current_text, the partial chunk goes
1197 * before that start though.
1199 advance_to_name_end (context);
1201 if (context->iter == context->current_text_end)
1203 /* The name hasn't necessarily ended. Merge with
1204 * partial chunk, leave state unchanged.
1206 add_to_partial (context, context->start, context->iter);
1208 else
1210 /* The name has ended. Combine it with the partial chunk
1211 * if any; push it on the stack; enter next state.
1213 add_to_partial (context, context->start, context->iter);
1214 push_partial_as_tag (context);
1216 context->state = STATE_BETWEEN_ATTRIBUTES;
1217 context->start = NULL;
1219 break;
1221 case STATE_INSIDE_ATTRIBUTE_NAME:
1222 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1224 advance_to_name_end (context);
1225 add_to_partial (context, context->start, context->iter);
1227 /* read the full name, if we enter the equals sign state
1228 * then add the attribute to the list (without the value),
1229 * otherwise store a partial chunk to be prepended later.
1231 if (context->iter != context->current_text_end)
1232 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1233 break;
1235 case STATE_AFTER_ATTRIBUTE_NAME:
1236 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1238 skip_spaces (context);
1240 if (context->iter != context->current_text_end)
1242 /* The name has ended. Combine it with the partial chunk
1243 * if any; push it on the stack; enter next state.
1245 if (!name_validate (context, context->partial_chunk->str, error))
1246 break;
1248 add_attribute (context, context->partial_chunk);
1250 context->partial_chunk = NULL;
1251 context->start = NULL;
1253 if (*context->iter == '=')
1255 advance_char (context);
1256 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1258 else
1260 gchar buf[8];
1262 set_error (context,
1263 error,
1264 G_MARKUP_ERROR_PARSE,
1265 _("Odd character '%s', expected a '=' after "
1266 "attribute name '%s' of element '%s'"),
1267 utf8_str (context->iter, buf),
1268 current_attribute (context),
1269 current_element (context));
1273 break;
1275 case STATE_BETWEEN_ATTRIBUTES:
1276 /* Possible next states: AFTER_CLOSE_ANGLE,
1277 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1279 skip_spaces (context);
1281 if (context->iter != context->current_text_end)
1283 if (*context->iter == '/')
1285 advance_char (context);
1286 context->state = STATE_AFTER_ELISION_SLASH;
1288 else if (*context->iter == '>')
1290 advance_char (context);
1291 context->state = STATE_AFTER_CLOSE_ANGLE;
1293 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1295 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1296 /* start of attribute name */
1297 context->start = context->iter;
1299 else
1301 gchar buf[8];
1303 set_error (context,
1304 error,
1305 G_MARKUP_ERROR_PARSE,
1306 _("Odd character '%s', expected a '>' or '/' "
1307 "character to end the start tag of "
1308 "element '%s', or optionally an attribute; "
1309 "perhaps you used an invalid character in "
1310 "an attribute name"),
1311 utf8_str (context->iter, buf),
1312 current_element (context));
1315 /* If we're done with attributes, invoke
1316 * the start_element callback
1318 if (context->state == STATE_AFTER_ELISION_SLASH ||
1319 context->state == STATE_AFTER_CLOSE_ANGLE)
1320 emit_start_element (context, error);
1322 break;
1324 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1325 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1327 skip_spaces (context);
1329 if (context->iter != context->current_text_end)
1331 if (*context->iter == '"')
1333 advance_char (context);
1334 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1335 context->start = context->iter;
1337 else if (*context->iter == '\'')
1339 advance_char (context);
1340 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1341 context->start = context->iter;
1343 else
1345 gchar buf[8];
1347 set_error (context,
1348 error,
1349 G_MARKUP_ERROR_PARSE,
1350 _("Odd character '%s', expected an open quote mark "
1351 "after the equals sign when giving value for "
1352 "attribute '%s' of element '%s'"),
1353 utf8_str (context->iter, buf),
1354 current_attribute (context),
1355 current_element (context));
1358 break;
1360 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1361 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1362 /* Possible next states: BETWEEN_ATTRIBUTES */
1364 gchar delim;
1366 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1368 delim = '\'';
1370 else
1372 delim = '"';
1377 if (*context->iter == delim)
1378 break;
1380 while (advance_char (context));
1382 if (context->iter == context->current_text_end)
1384 /* The value hasn't necessarily ended. Merge with
1385 * partial chunk, leave state unchanged.
1387 add_to_partial (context, context->start, context->iter);
1389 else
1391 gboolean is_ascii;
1392 /* The value has ended at the quote mark. Combine it
1393 * with the partial chunk if any; set it for the current
1394 * attribute.
1396 add_to_partial (context, context->start, context->iter);
1398 g_assert (context->cur_attr >= 0);
1400 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1401 (is_ascii || text_validate (context, context->partial_chunk->str,
1402 context->partial_chunk->len, error)))
1404 /* success, advance past quote and set state. */
1405 context->attr_values[context->cur_attr] = context->partial_chunk;
1406 context->partial_chunk = NULL;
1407 advance_char (context);
1408 context->state = STATE_BETWEEN_ATTRIBUTES;
1409 context->start = NULL;
1412 truncate_partial (context);
1414 break;
1416 case STATE_INSIDE_TEXT:
1417 /* Possible next states: AFTER_OPEN_ANGLE */
1420 if (*context->iter == '<')
1421 break;
1423 while (advance_char (context));
1425 /* The text hasn't necessarily ended. Merge with
1426 * partial chunk, leave state unchanged.
1429 add_to_partial (context, context->start, context->iter);
1431 if (context->iter != context->current_text_end)
1433 gboolean is_ascii;
1435 /* The text has ended at the open angle. Call the text
1436 * callback.
1438 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1439 (is_ascii || text_validate (context, context->partial_chunk->str,
1440 context->partial_chunk->len, error)))
1442 GError *tmp_error = NULL;
1444 if (context->parser->text)
1445 (*context->parser->text) (context,
1446 context->partial_chunk->str,
1447 context->partial_chunk->len,
1448 context->user_data,
1449 &tmp_error);
1451 if (tmp_error == NULL)
1453 /* advance past open angle and set state. */
1454 advance_char (context);
1455 context->state = STATE_AFTER_OPEN_ANGLE;
1456 /* could begin a passthrough */
1457 context->start = context->iter;
1459 else
1460 propagate_error (context, error, tmp_error);
1463 truncate_partial (context);
1465 break;
1467 case STATE_AFTER_CLOSE_TAG_SLASH:
1468 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1469 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1471 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1473 /* start of tag name */
1474 context->start = context->iter;
1476 else
1478 gchar buf[8];
1480 set_error (context,
1481 error,
1482 G_MARKUP_ERROR_PARSE,
1483 _("'%s' is not a valid character following "
1484 "the characters '</'; '%s' may not begin an "
1485 "element name"),
1486 utf8_str (context->iter, buf),
1487 utf8_str (context->iter, buf));
1489 break;
1491 case STATE_INSIDE_CLOSE_TAG_NAME:
1492 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1493 advance_to_name_end (context);
1494 add_to_partial (context, context->start, context->iter);
1496 if (context->iter != context->current_text_end)
1497 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1498 break;
1500 case STATE_AFTER_CLOSE_TAG_NAME:
1501 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1503 skip_spaces (context);
1505 if (context->iter != context->current_text_end)
1507 GString *close_name;
1509 close_name = context->partial_chunk;
1510 context->partial_chunk = NULL;
1512 if (*context->iter != '>')
1514 gchar buf[8];
1516 set_error (context,
1517 error,
1518 G_MARKUP_ERROR_PARSE,
1519 _("'%s' is not a valid character following "
1520 "the close element name '%s'; the allowed "
1521 "character is '>'"),
1522 utf8_str (context->iter, buf),
1523 close_name->str);
1525 else if (context->tag_stack == NULL)
1527 set_error (context,
1528 error,
1529 G_MARKUP_ERROR_PARSE,
1530 _("Element '%s' was closed, no element "
1531 "is currently open"),
1532 close_name->str);
1534 else if (strcmp (close_name->str, current_element (context)) != 0)
1536 set_error (context,
1537 error,
1538 G_MARKUP_ERROR_PARSE,
1539 _("Element '%s' was closed, but the currently "
1540 "open element is '%s'"),
1541 close_name->str,
1542 current_element (context));
1544 else
1546 GError *tmp_error;
1547 advance_char (context);
1548 context->state = STATE_AFTER_CLOSE_ANGLE;
1549 context->start = NULL;
1551 possibly_finish_subparser (context);
1553 /* call the end_element callback */
1554 tmp_error = NULL;
1555 if (context->parser->end_element)
1556 (* context->parser->end_element) (context,
1557 close_name->str,
1558 context->user_data,
1559 &tmp_error);
1561 ensure_no_outstanding_subparser (context);
1562 pop_tag (context);
1564 if (tmp_error)
1565 propagate_error (context, error, tmp_error);
1567 context->partial_chunk = close_name;
1568 truncate_partial (context);
1570 break;
1572 case STATE_INSIDE_PASSTHROUGH:
1573 /* Possible next state: AFTER_CLOSE_ANGLE */
1576 if (*context->iter == '<')
1577 context->balance++;
1578 if (*context->iter == '>')
1580 gchar *str;
1581 gsize len;
1583 context->balance--;
1584 add_to_partial (context, context->start, context->iter);
1585 context->start = context->iter;
1587 str = context->partial_chunk->str;
1588 len = context->partial_chunk->len;
1590 if (str[1] == '?' && str[len - 1] == '?')
1591 break;
1592 if (strncmp (str, "<!--", 4) == 0 &&
1593 strcmp (str + len - 2, "--") == 0)
1594 break;
1595 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1596 strcmp (str + len - 2, "]]") == 0)
1597 break;
1598 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1599 context->balance == 0)
1600 break;
1603 while (advance_char (context));
1605 if (context->iter == context->current_text_end)
1607 /* The passthrough hasn't necessarily ended. Merge with
1608 * partial chunk, leave state unchanged.
1610 add_to_partial (context, context->start, context->iter);
1612 else
1614 /* The passthrough has ended at the close angle. Combine
1615 * it with the partial chunk if any. Call the passthrough
1616 * callback. Note that the open/close angles are
1617 * included in the text of the passthrough.
1619 GError *tmp_error = NULL;
1621 advance_char (context); /* advance past close angle */
1622 add_to_partial (context, context->start, context->iter);
1624 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1625 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1627 if (context->parser->text &&
1628 text_validate (context,
1629 context->partial_chunk->str + 9,
1630 context->partial_chunk->len - 12,
1631 error))
1632 (*context->parser->text) (context,
1633 context->partial_chunk->str + 9,
1634 context->partial_chunk->len - 12,
1635 context->user_data,
1636 &tmp_error);
1638 else if (context->parser->passthrough &&
1639 text_validate (context,
1640 context->partial_chunk->str,
1641 context->partial_chunk->len,
1642 error))
1643 (*context->parser->passthrough) (context,
1644 context->partial_chunk->str,
1645 context->partial_chunk->len,
1646 context->user_data,
1647 &tmp_error);
1649 truncate_partial (context);
1651 if (tmp_error == NULL)
1653 context->state = STATE_AFTER_CLOSE_ANGLE;
1654 context->start = context->iter; /* could begin text */
1656 else
1657 propagate_error (context, error, tmp_error);
1659 break;
1661 case STATE_ERROR:
1662 goto finished;
1663 break;
1665 default:
1666 g_assert_not_reached ();
1667 break;
1671 finished:
1672 context->parsing = FALSE;
1674 return context->state != STATE_ERROR;
1678 * g_markup_parse_context_end_parse:
1679 * @context: a #GMarkupParseContext
1680 * @error: return location for a #GError
1682 * Signals to the #GMarkupParseContext that all data has been
1683 * fed into the parse context with g_markup_parse_context_parse().
1685 * This function reports an error if the document isn't complete,
1686 * for example if elements are still open.
1688 * Return value: %TRUE on success, %FALSE if an error was set
1690 gboolean
1691 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1692 GError **error)
1694 g_return_val_if_fail (context != NULL, FALSE);
1695 g_return_val_if_fail (!context->parsing, FALSE);
1696 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1698 if (context->partial_chunk != NULL)
1700 g_string_free (context->partial_chunk, TRUE);
1701 context->partial_chunk = NULL;
1704 if (context->document_empty)
1706 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1707 _("Document was empty or contained only whitespace"));
1708 return FALSE;
1711 context->parsing = TRUE;
1713 switch (context->state)
1715 case STATE_START:
1716 /* Nothing to do */
1717 break;
1719 case STATE_AFTER_OPEN_ANGLE:
1720 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1721 _("Document ended unexpectedly just after an open angle bracket '<'"));
1722 break;
1724 case STATE_AFTER_CLOSE_ANGLE:
1725 if (context->tag_stack != NULL)
1727 /* Error message the same as for INSIDE_TEXT */
1728 set_error (context, error, G_MARKUP_ERROR_PARSE,
1729 _("Document ended unexpectedly with elements still open - "
1730 "'%s' was the last element opened"),
1731 current_element (context));
1733 break;
1735 case STATE_AFTER_ELISION_SLASH:
1736 set_error (context, error, G_MARKUP_ERROR_PARSE,
1737 _("Document ended unexpectedly, expected to see a close angle "
1738 "bracket ending the tag <%s/>"), current_element (context));
1739 break;
1741 case STATE_INSIDE_OPEN_TAG_NAME:
1742 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1743 _("Document ended unexpectedly inside an element name"));
1744 break;
1746 case STATE_INSIDE_ATTRIBUTE_NAME:
1747 case STATE_AFTER_ATTRIBUTE_NAME:
1748 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1749 _("Document ended unexpectedly inside an attribute name"));
1750 break;
1752 case STATE_BETWEEN_ATTRIBUTES:
1753 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1754 _("Document ended unexpectedly inside an element-opening "
1755 "tag."));
1756 break;
1758 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1759 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1760 _("Document ended unexpectedly after the equals sign "
1761 "following an attribute name; no attribute value"));
1762 break;
1764 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1765 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1766 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1767 _("Document ended unexpectedly while inside an attribute "
1768 "value"));
1769 break;
1771 case STATE_INSIDE_TEXT:
1772 g_assert (context->tag_stack != NULL);
1773 set_error (context, error, G_MARKUP_ERROR_PARSE,
1774 _("Document ended unexpectedly with elements still open - "
1775 "'%s' was the last element opened"),
1776 current_element (context));
1777 break;
1779 case STATE_AFTER_CLOSE_TAG_SLASH:
1780 case STATE_INSIDE_CLOSE_TAG_NAME:
1781 case STATE_AFTER_CLOSE_TAG_NAME:
1782 set_error (context, error, G_MARKUP_ERROR_PARSE,
1783 _("Document ended unexpectedly inside the close tag for "
1784 "element '%s'"), current_element (context));
1785 break;
1787 case STATE_INSIDE_PASSTHROUGH:
1788 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1789 _("Document ended unexpectedly inside a comment or "
1790 "processing instruction"));
1791 break;
1793 case STATE_ERROR:
1794 default:
1795 g_assert_not_reached ();
1796 break;
1799 context->parsing = FALSE;
1801 return context->state != STATE_ERROR;
1805 * g_markup_parse_context_get_element:
1806 * @context: a #GMarkupParseContext
1808 * Retrieves the name of the currently open element.
1810 * If called from the start_element or end_element handlers this will
1811 * give the element_name as passed to those functions. For the parent
1812 * elements, see g_markup_parse_context_get_element_stack().
1814 * Returns: the name of the currently open element, or %NULL
1816 * Since: 2.2
1818 const gchar *
1819 g_markup_parse_context_get_element (GMarkupParseContext *context)
1821 g_return_val_if_fail (context != NULL, NULL);
1823 if (context->tag_stack == NULL)
1824 return NULL;
1825 else
1826 return current_element (context);
1830 * g_markup_parse_context_get_element_stack:
1831 * @context: a #GMarkupParseContext
1833 * Retrieves the element stack from the internal state of the parser.
1835 * The returned #GSList is a list of strings where the first item is
1836 * the currently open tag (as would be returned by
1837 * g_markup_parse_context_get_element()) and the next item is its
1838 * immediate parent.
1840 * This function is intended to be used in the start_element and
1841 * end_element handlers where g_markup_parse_context_get_element()
1842 * would merely return the name of the element that is being
1843 * processed.
1845 * Returns: the element stack, which must not be modified
1847 * Since: 2.16
1849 const GSList *
1850 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1852 g_return_val_if_fail (context != NULL, NULL);
1853 return context->tag_stack;
1857 * g_markup_parse_context_get_position:
1858 * @context: a #GMarkupParseContext
1859 * @line_number: (allow-none): return location for a line number, or %NULL
1860 * @char_number: (allow-none): return location for a char-on-line number, or %NULL
1862 * Retrieves the current line number and the number of the character on
1863 * that line. Intended for use in error messages; there are no strict
1864 * semantics for what constitutes the "current" line number other than
1865 * "the best number we could come up with for error messages."
1867 void
1868 g_markup_parse_context_get_position (GMarkupParseContext *context,
1869 gint *line_number,
1870 gint *char_number)
1872 g_return_if_fail (context != NULL);
1874 if (line_number)
1875 *line_number = context->line_number;
1877 if (char_number)
1878 *char_number = context->char_number;
1882 * g_markup_parse_context_get_user_data:
1883 * @context: a #GMarkupParseContext
1885 * Returns the user_data associated with @context.
1887 * This will either be the user_data that was provided to
1888 * g_markup_parse_context_new() or to the most recent call
1889 * of g_markup_parse_context_push().
1891 * Returns: the provided user_data. The returned data belongs to
1892 * the markup context and will be freed when
1893 * g_markup_parse_context_free() is called.
1895 * Since: 2.18
1897 gpointer
1898 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1900 return context->user_data;
1904 * g_markup_parse_context_push:
1905 * @context: a #GMarkupParseContext
1906 * @parser: a #GMarkupParser
1907 * @user_data: user data to pass to #GMarkupParser functions
1909 * Temporarily redirects markup data to a sub-parser.
1911 * This function may only be called from the start_element handler of
1912 * a #GMarkupParser. It must be matched with a corresponding call to
1913 * g_markup_parse_context_pop() in the matching end_element handler
1914 * (except in the case that the parser aborts due to an error).
1916 * All tags, text and other data between the matching tags is
1917 * redirected to the subparser given by @parser. @user_data is used
1918 * as the user_data for that parser. @user_data is also passed to the
1919 * error callback in the event that an error occurs. This includes
1920 * errors that occur in subparsers of the subparser.
1922 * The end tag matching the start tag for which this call was made is
1923 * handled by the previous parser (which is given its own user_data)
1924 * which is why g_markup_parse_context_pop() is provided to allow "one
1925 * last access" to the @user_data provided to this function. In the
1926 * case of error, the @user_data provided here is passed directly to
1927 * the error callback of the subparser and g_markup_parse_context_pop()
1928 * should not be called. In either case, if @user_data was allocated
1929 * then it ought to be freed from both of these locations.
1931 * This function is not intended to be directly called by users
1932 * interested in invoking subparsers. Instead, it is intended to be
1933 * used by the subparsers themselves to implement a higher-level
1934 * interface.
1936 * As an example, see the following implementation of a simple
1937 * parser that counts the number of tags encountered.
1939 * |[
1940 * typedef struct
1942 * gint tag_count;
1943 * } CounterData;
1945 * static void
1946 * counter_start_element (GMarkupParseContext *context,
1947 * const gchar *element_name,
1948 * const gchar **attribute_names,
1949 * const gchar **attribute_values,
1950 * gpointer user_data,
1951 * GError **error)
1953 * CounterData *data = user_data;
1955 * data->tag_count++;
1958 * static void
1959 * counter_error (GMarkupParseContext *context,
1960 * GError *error,
1961 * gpointer user_data)
1963 * CounterData *data = user_data;
1965 * g_slice_free (CounterData, data);
1968 * static GMarkupParser counter_subparser =
1970 * counter_start_element,
1971 * NULL,
1972 * NULL,
1973 * NULL,
1974 * counter_error
1975 * };
1976 * ]|
1978 * In order to allow this parser to be easily used as a subparser, the
1979 * following interface is provided:
1981 * |[
1982 * void
1983 * start_counting (GMarkupParseContext *context)
1985 * CounterData *data = g_slice_new (CounterData);
1987 * data->tag_count = 0;
1988 * g_markup_parse_context_push (context, &counter_subparser, data);
1991 * gint
1992 * end_counting (GMarkupParseContext *context)
1994 * CounterData *data = g_markup_parse_context_pop (context);
1995 * int result;
1997 * result = data->tag_count;
1998 * g_slice_free (CounterData, data);
2000 * return result;
2002 * ]|
2004 * The subparser would then be used as follows:
2006 * |[
2007 * static void start_element (context, element_name, ...)
2009 * if (strcmp (element_name, "count-these") == 0)
2010 * start_counting (context);
2012 * /&ast; else, handle other tags... &ast;/
2015 * static void end_element (context, element_name, ...)
2017 * if (strcmp (element_name, "count-these") == 0)
2018 * g_print ("Counted %d tags\n", end_counting (context));
2020 * /&ast; else, handle other tags... &ast;/
2022 * ]|
2024 * Since: 2.18
2026 void
2027 g_markup_parse_context_push (GMarkupParseContext *context,
2028 const GMarkupParser *parser,
2029 gpointer user_data)
2031 GMarkupRecursionTracker *tracker;
2033 tracker = g_slice_new (GMarkupRecursionTracker);
2034 tracker->prev_element = context->subparser_element;
2035 tracker->prev_parser = context->parser;
2036 tracker->prev_user_data = context->user_data;
2038 context->subparser_element = current_element (context);
2039 context->parser = parser;
2040 context->user_data = user_data;
2042 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2043 tracker);
2047 * g_markup_parse_context_pop:
2048 * @context: a #GMarkupParseContext
2050 * Completes the process of a temporary sub-parser redirection.
2052 * This function exists to collect the user_data allocated by a
2053 * matching call to g_markup_parse_context_push(). It must be called
2054 * in the end_element handler corresponding to the start_element
2055 * handler during which g_markup_parse_context_push() was called.
2056 * You must not call this function from the error callback -- the
2057 * @user_data is provided directly to the callback in that case.
2059 * This function is not intended to be directly called by users
2060 * interested in invoking subparsers. Instead, it is intended to
2061 * be used by the subparsers themselves to implement a higher-level
2062 * interface.
2064 * Returns: the user data passed to g_markup_parse_context_push()
2066 * Since: 2.18
2068 gpointer
2069 g_markup_parse_context_pop (GMarkupParseContext *context)
2071 gpointer user_data;
2073 if (!context->awaiting_pop)
2074 possibly_finish_subparser (context);
2076 g_assert (context->awaiting_pop);
2078 context->awaiting_pop = FALSE;
2080 /* valgrind friendliness */
2081 user_data = context->held_user_data;
2082 context->held_user_data = NULL;
2084 return user_data;
2087 static void
2088 append_escaped_text (GString *str,
2089 const gchar *text,
2090 gssize length)
2092 const gchar *p;
2093 const gchar *end;
2094 gunichar c;
2096 p = text;
2097 end = text + length;
2099 while (p != end)
2101 const gchar *next;
2102 next = g_utf8_next_char (p);
2104 switch (*p)
2106 case '&':
2107 g_string_append (str, "&amp;");
2108 break;
2110 case '<':
2111 g_string_append (str, "&lt;");
2112 break;
2114 case '>':
2115 g_string_append (str, "&gt;");
2116 break;
2118 case '\'':
2119 g_string_append (str, "&apos;");
2120 break;
2122 case '"':
2123 g_string_append (str, "&quot;");
2124 break;
2126 default:
2127 c = g_utf8_get_char (p);
2128 if ((0x1 <= c && c <= 0x8) ||
2129 (0xb <= c && c <= 0xc) ||
2130 (0xe <= c && c <= 0x1f) ||
2131 (0x7f <= c && c <= 0x84) ||
2132 (0x86 <= c && c <= 0x9f))
2133 g_string_append_printf (str, "&#x%x;", c);
2134 else
2135 g_string_append_len (str, p, next - p);
2136 break;
2139 p = next;
2144 * g_markup_escape_text:
2145 * @text: some valid UTF-8 text
2146 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2148 * Escapes text so that the markup parser will parse it verbatim.
2149 * Less than, greater than, ampersand, etc. are replaced with the
2150 * corresponding entities. This function would typically be used
2151 * when writing out a file to be parsed with the markup parser.
2153 * Note that this function doesn't protect whitespace and line endings
2154 * from being processed according to the XML rules for normalization
2155 * of line endings and attribute values.
2157 * Note also that this function will produce character references in
2158 * the range of &amp;#x1; ... &amp;#x1f; for all control sequences
2159 * except for tabstop, newline and carriage return. The character
2160 * references in this range are not valid XML 1.0, but they are
2161 * valid XML 1.1 and will be accepted by the GMarkup parser.
2163 * Return value: a newly allocated string with the escaped text
2165 gchar*
2166 g_markup_escape_text (const gchar *text,
2167 gssize length)
2169 GString *str;
2171 g_return_val_if_fail (text != NULL, NULL);
2173 if (length < 0)
2174 length = strlen (text);
2176 /* prealloc at least as long as original text */
2177 str = g_string_sized_new (length);
2178 append_escaped_text (str, text, length);
2180 return g_string_free (str, FALSE);
2184 * find_conversion:
2185 * @format: a printf-style format string
2186 * @after: location to store a pointer to the character after
2187 * the returned conversion. On a %NULL return, returns the
2188 * pointer to the trailing NUL in the string
2190 * Find the next conversion in a printf-style format string.
2191 * Partially based on code from printf-parser.c,
2192 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2194 * Return value: pointer to the next conversion in @format,
2195 * or %NULL, if none.
2197 static const char *
2198 find_conversion (const char *format,
2199 const char **after)
2201 const char *start = format;
2202 const char *cp;
2204 while (*start != '\0' && *start != '%')
2205 start++;
2207 if (*start == '\0')
2209 *after = start;
2210 return NULL;
2213 cp = start + 1;
2215 if (*cp == '\0')
2217 *after = cp;
2218 return NULL;
2221 /* Test for positional argument. */
2222 if (*cp >= '0' && *cp <= '9')
2224 const char *np;
2226 for (np = cp; *np >= '0' && *np <= '9'; np++)
2228 if (*np == '$')
2229 cp = np + 1;
2232 /* Skip the flags. */
2233 for (;;)
2235 if (*cp == '\'' ||
2236 *cp == '-' ||
2237 *cp == '+' ||
2238 *cp == ' ' ||
2239 *cp == '#' ||
2240 *cp == '0')
2241 cp++;
2242 else
2243 break;
2246 /* Skip the field width. */
2247 if (*cp == '*')
2249 cp++;
2251 /* Test for positional argument. */
2252 if (*cp >= '0' && *cp <= '9')
2254 const char *np;
2256 for (np = cp; *np >= '0' && *np <= '9'; np++)
2258 if (*np == '$')
2259 cp = np + 1;
2262 else
2264 for (; *cp >= '0' && *cp <= '9'; cp++)
2268 /* Skip the precision. */
2269 if (*cp == '.')
2271 cp++;
2272 if (*cp == '*')
2274 /* Test for positional argument. */
2275 if (*cp >= '0' && *cp <= '9')
2277 const char *np;
2279 for (np = cp; *np >= '0' && *np <= '9'; np++)
2281 if (*np == '$')
2282 cp = np + 1;
2285 else
2287 for (; *cp >= '0' && *cp <= '9'; cp++)
2292 /* Skip argument type/size specifiers. */
2293 while (*cp == 'h' ||
2294 *cp == 'L' ||
2295 *cp == 'l' ||
2296 *cp == 'j' ||
2297 *cp == 'z' ||
2298 *cp == 'Z' ||
2299 *cp == 't')
2300 cp++;
2302 /* Skip the conversion character. */
2303 cp++;
2305 *after = cp;
2306 return start;
2310 * g_markup_vprintf_escaped:
2311 * @format: printf() style format string
2312 * @args: variable argument list, similar to vprintf()
2314 * Formats the data in @args according to @format, escaping
2315 * all string and character arguments in the fashion
2316 * of g_markup_escape_text(). See g_markup_printf_escaped().
2318 * Return value: newly allocated result from formatting
2319 * operation. Free with g_free().
2321 * Since: 2.4
2323 gchar *
2324 g_markup_vprintf_escaped (const gchar *format,
2325 va_list args)
2327 GString *format1;
2328 GString *format2;
2329 GString *result = NULL;
2330 gchar *output1 = NULL;
2331 gchar *output2 = NULL;
2332 const char *p, *op1, *op2;
2333 va_list args2;
2335 /* The technique here, is that we make two format strings that
2336 * have the identical conversions in the identical order to the
2337 * original strings, but differ in the text in-between. We
2338 * then use the normal g_strdup_vprintf() to format the arguments
2339 * with the two new format strings. By comparing the results,
2340 * we can figure out what segments of the output come from
2341 * the original format string, and what from the arguments,
2342 * and thus know what portions of the string to escape.
2344 * For instance, for:
2346 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2348 * We form the two format strings "%sX%dX" and %sY%sY". The results
2349 * of formatting with those two strings are
2351 * "%sX%dX" => "Susan & FredX5X"
2352 * "%sY%dY" => "Susan & FredY5Y"
2354 * To find the span of the first argument, we find the first position
2355 * where the two arguments differ, which tells us that the first
2356 * argument formatted to "Susan & Fred". We then escape that
2357 * to "Susan &amp; Fred" and join up with the intermediate portions
2358 * of the format string and the second argument to get
2359 * "Susan &amp; Fred ate 5 apples".
2362 /* Create the two modified format strings
2364 format1 = g_string_new (NULL);
2365 format2 = g_string_new (NULL);
2366 p = format;
2367 while (TRUE)
2369 const char *after;
2370 const char *conv = find_conversion (p, &after);
2371 if (!conv)
2372 break;
2374 g_string_append_len (format1, conv, after - conv);
2375 g_string_append_c (format1, 'X');
2376 g_string_append_len (format2, conv, after - conv);
2377 g_string_append_c (format2, 'Y');
2379 p = after;
2382 /* Use them to format the arguments
2384 G_VA_COPY (args2, args);
2386 output1 = g_strdup_vprintf (format1->str, args);
2387 if (!output1)
2389 va_end (args2);
2390 goto cleanup;
2393 output2 = g_strdup_vprintf (format2->str, args2);
2394 va_end (args2);
2395 if (!output2)
2396 goto cleanup;
2398 result = g_string_new (NULL);
2400 /* Iterate through the original format string again,
2401 * copying the non-conversion portions and the escaped
2402 * converted arguments to the output string.
2404 op1 = output1;
2405 op2 = output2;
2406 p = format;
2407 while (TRUE)
2409 const char *after;
2410 const char *output_start;
2411 const char *conv = find_conversion (p, &after);
2412 char *escaped;
2414 if (!conv) /* The end, after points to the trailing \0 */
2416 g_string_append_len (result, p, after - p);
2417 break;
2420 g_string_append_len (result, p, conv - p);
2421 output_start = op1;
2422 while (*op1 == *op2)
2424 op1++;
2425 op2++;
2428 escaped = g_markup_escape_text (output_start, op1 - output_start);
2429 g_string_append (result, escaped);
2430 g_free (escaped);
2432 p = after;
2433 op1++;
2434 op2++;
2437 cleanup:
2438 g_string_free (format1, TRUE);
2439 g_string_free (format2, TRUE);
2440 g_free (output1);
2441 g_free (output2);
2443 if (result)
2444 return g_string_free (result, FALSE);
2445 else
2446 return NULL;
2450 * g_markup_printf_escaped:
2451 * @format: printf() style format string
2452 * @...: the arguments to insert in the format string
2454 * Formats arguments according to @format, escaping
2455 * all string and character arguments in the fashion
2456 * of g_markup_escape_text(). This is useful when you
2457 * want to insert literal strings into XML-style markup
2458 * output, without having to worry that the strings
2459 * might themselves contain markup.
2461 * |[
2462 * const char *store = "Fortnum &amp; Mason";
2463 * const char *item = "Tea";
2464 * char *output;
2465 * &nbsp;
2466 * output = g_markup_printf_escaped ("&lt;purchase&gt;"
2467 * "&lt;store&gt;&percnt;s&lt;/store&gt;"
2468 * "&lt;item&gt;&percnt;s&lt;/item&gt;"
2469 * "&lt;/purchase&gt;",
2470 * store, item);
2471 * ]|
2473 * Return value: newly allocated result from formatting
2474 * operation. Free with g_free().
2476 * Since: 2.4
2478 gchar *
2479 g_markup_printf_escaped (const gchar *format, ...)
2481 char *result;
2482 va_list args;
2484 va_start (args, format);
2485 result = g_markup_vprintf_escaped (format, args);
2486 va_end (args);
2488 return result;
2491 static gboolean
2492 g_markup_parse_boolean (const char *string,
2493 gboolean *value)
2495 char const * const falses[] = { "false", "f", "no", "n", "0" };
2496 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2497 int i;
2499 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2501 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2503 if (value != NULL)
2504 *value = FALSE;
2506 return TRUE;
2510 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2512 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2514 if (value != NULL)
2515 *value = TRUE;
2517 return TRUE;
2521 return FALSE;
2525 * GMarkupCollectType:
2526 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2527 * to collect
2528 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2529 * the attribute_values[] array. Expects a parameter of type (const
2530 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2531 * attribute isn't present then the pointer will be set to %NULL
2532 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2533 * expects a parameter of type (char **) and g_strdup()s the
2534 * returned pointer. The pointer must be freed with g_free()
2535 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2536 * and parses the attribute value as a boolean. Sets %FALSE if the
2537 * attribute isn't present. Valid boolean values consist of
2538 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2539 * "yes", "y", "1"
2540 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2541 * in the case of a missing attribute a value is set that compares
2542 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2543 * implied
2544 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2545 * If present, allows the attribute not to appear. A default value
2546 * is set depending on what value type is used
2548 * A mixed enumerated type and flags field. You must specify one type
2549 * (string, strdup, boolean, tristate). Additionally, you may optionally
2550 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2552 * It is likely that this enum will be extended in the future to
2553 * support other types.
2557 * g_markup_collect_attributes:
2558 * @element_name: the current tag name
2559 * @attribute_names: the attribute names
2560 * @attribute_values: the attribute values
2561 * @error: a pointer to a #GError or %NULL
2562 * @first_type: the #GMarkupCollectType of the first attribute
2563 * @first_attr: the name of the first attribute
2564 * @...: a pointer to the storage location of the first attribute
2565 * (or %NULL), followed by more types names and pointers, ending
2566 * with %G_MARKUP_COLLECT_INVALID
2568 * Collects the attributes of the element from the data passed to the
2569 * #GMarkupParser start_element function, dealing with common error
2570 * conditions and supporting boolean values.
2572 * This utility function is not required to write a parser but can save
2573 * a lot of typing.
2575 * The @element_name, @attribute_names, @attribute_values and @error
2576 * parameters passed to the start_element callback should be passed
2577 * unmodified to this function.
2579 * Following these arguments is a list of "supported" attributes to collect.
2580 * It is an error to specify multiple attributes with the same name. If any
2581 * attribute not in the list appears in the @attribute_names array then an
2582 * unknown attribute error will result.
2584 * The #GMarkupCollectType field allows specifying the type of collection
2585 * to perform and if a given attribute must appear or is optional.
2587 * The attribute name is simply the name of the attribute to collect.
2589 * The pointer should be of the appropriate type (see the descriptions
2590 * under #GMarkupCollectType) and may be %NULL in case a particular
2591 * attribute is to be allowed but ignored.
2593 * This function deals with issuing errors for missing attributes
2594 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2595 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2596 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2597 * as parse errors for boolean-valued attributes (again of type
2598 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2599 * will be returned and @error will be set as appropriate.
2601 * Return value: %TRUE if successful
2603 * Since: 2.16
2605 gboolean
2606 g_markup_collect_attributes (const gchar *element_name,
2607 const gchar **attribute_names,
2608 const gchar **attribute_values,
2609 GError **error,
2610 GMarkupCollectType first_type,
2611 const gchar *first_attr,
2612 ...)
2614 GMarkupCollectType type;
2615 const gchar *attr;
2616 guint64 collected;
2617 int written;
2618 va_list ap;
2619 int i;
2621 type = first_type;
2622 attr = first_attr;
2623 collected = 0;
2624 written = 0;
2626 va_start (ap, first_attr);
2627 while (type != G_MARKUP_COLLECT_INVALID)
2629 gboolean mandatory;
2630 const gchar *value;
2632 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2633 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2635 /* tristate records a value != TRUE and != FALSE
2636 * for the case where the attribute is missing
2638 if (type == G_MARKUP_COLLECT_TRISTATE)
2639 mandatory = FALSE;
2641 for (i = 0; attribute_names[i]; i++)
2642 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2643 if (!strcmp (attribute_names[i], attr))
2644 break;
2646 /* ISO C99 only promises that the user can pass up to 127 arguments.
2647 * Subtracting the first 4 arguments plus the final NULL and dividing
2648 * by 3 arguments per collected attribute, we are left with a maximum
2649 * number of supported attributes of (127 - 5) / 3 = 40.
2651 * In reality, nobody is ever going to call us with anywhere close to
2652 * 40 attributes to collect, so it is safe to assume that if i > 40
2653 * then the user has given some invalid or repeated arguments. These
2654 * problems will be caught and reported at the end of the function.
2656 * We know at this point that we have an error, but we don't know
2657 * what error it is, so just continue...
2659 if (i < 40)
2660 collected |= (G_GUINT64_CONSTANT(1) << i);
2662 value = attribute_values[i];
2664 if (value == NULL && mandatory)
2666 g_set_error (error, G_MARKUP_ERROR,
2667 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2668 "element '%s' requires attribute '%s'",
2669 element_name, attr);
2671 va_end (ap);
2672 goto failure;
2675 switch (type)
2677 case G_MARKUP_COLLECT_STRING:
2679 const char **str_ptr;
2681 str_ptr = va_arg (ap, const char **);
2683 if (str_ptr != NULL)
2684 *str_ptr = value;
2686 break;
2688 case G_MARKUP_COLLECT_STRDUP:
2690 char **str_ptr;
2692 str_ptr = va_arg (ap, char **);
2694 if (str_ptr != NULL)
2695 *str_ptr = g_strdup (value);
2697 break;
2699 case G_MARKUP_COLLECT_BOOLEAN:
2700 case G_MARKUP_COLLECT_TRISTATE:
2701 if (value == NULL)
2703 gboolean *bool_ptr;
2705 bool_ptr = va_arg (ap, gboolean *);
2707 if (bool_ptr != NULL)
2709 if (type == G_MARKUP_COLLECT_TRISTATE)
2710 /* constructivists rejoice!
2711 * neither false nor true...
2713 *bool_ptr = -1;
2715 else /* G_MARKUP_COLLECT_BOOLEAN */
2716 *bool_ptr = FALSE;
2719 else
2721 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2723 g_set_error (error, G_MARKUP_ERROR,
2724 G_MARKUP_ERROR_INVALID_CONTENT,
2725 "element '%s', attribute '%s', value '%s' "
2726 "cannot be parsed as a boolean value",
2727 element_name, attr, value);
2729 va_end (ap);
2730 goto failure;
2734 break;
2736 default:
2737 g_assert_not_reached ();
2740 type = va_arg (ap, GMarkupCollectType);
2741 attr = va_arg (ap, const char *);
2742 written++;
2744 va_end (ap);
2746 /* ensure we collected all the arguments */
2747 for (i = 0; attribute_names[i]; i++)
2748 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2750 /* attribute not collected: could be caused by two things.
2752 * 1) it doesn't exist in our list of attributes
2753 * 2) it existed but was matched by a duplicate attribute earlier
2755 * find out.
2757 int j;
2759 for (j = 0; j < i; j++)
2760 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2761 /* duplicate! */
2762 break;
2764 /* j is now the first occurrence of attribute_names[i] */
2765 if (i == j)
2766 g_set_error (error, G_MARKUP_ERROR,
2767 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2768 "attribute '%s' invalid for element '%s'",
2769 attribute_names[i], element_name);
2770 else
2771 g_set_error (error, G_MARKUP_ERROR,
2772 G_MARKUP_ERROR_INVALID_CONTENT,
2773 "attribute '%s' given multiple times for element '%s'",
2774 attribute_names[i], element_name);
2776 goto failure;
2779 return TRUE;
2781 failure:
2782 /* replay the above to free allocations */
2783 type = first_type;
2784 attr = first_attr;
2786 va_start (ap, first_attr);
2787 while (type != G_MARKUP_COLLECT_INVALID)
2789 gpointer ptr;
2791 ptr = va_arg (ap, gpointer);
2793 if (ptr != NULL)
2795 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2797 case G_MARKUP_COLLECT_STRDUP:
2798 if (written)
2799 g_free (*(char **) ptr);
2801 case G_MARKUP_COLLECT_STRING:
2802 *(char **) ptr = NULL;
2803 break;
2805 case G_MARKUP_COLLECT_BOOLEAN:
2806 *(gboolean *) ptr = FALSE;
2807 break;
2809 case G_MARKUP_COLLECT_TRISTATE:
2810 *(gboolean *) ptr = -1;
2811 break;
2815 type = va_arg (ap, GMarkupCollectType);
2816 attr = va_arg (ap, const char *);
2818 va_end (ap);
2820 return FALSE;