Const 'parser' arg to g_markup_parse_context_push
[platform/upstream/glib.git] / glib / gmarkup.c
1 /* gmarkup.c - Simple XML-like parser
2  *
3  *  Copyright 2000, 2003 Red Hat, Inc.
4  *  Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
5  *
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.
10  *
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.
15  *
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.
20  */
21
22 #include "config.h"
23
24 #include <stdarg.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
29
30 #include "gmarkup.h"
31
32 #include "galloca.h"
33 #include "gstrfuncs.h"
34 #include "gstring.h"
35 #include "gtestutils.h"
36 #include "glibintl.h"
37
38 GQuark
39 g_markup_error_quark (void)
40 {
41   return g_quark_from_static_string ("g-markup-error-quark");
42 }
43
44 typedef enum
45 {
46   STATE_START,
47   STATE_AFTER_OPEN_ANGLE,
48   STATE_AFTER_CLOSE_ANGLE,
49   STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
50   STATE_INSIDE_OPEN_TAG_NAME,
51   STATE_INSIDE_ATTRIBUTE_NAME,
52   STATE_AFTER_ATTRIBUTE_NAME,
53   STATE_BETWEEN_ATTRIBUTES,
54   STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
55   STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
56   STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
57   STATE_INSIDE_TEXT,
58   STATE_AFTER_CLOSE_TAG_SLASH,
59   STATE_INSIDE_CLOSE_TAG_NAME,
60   STATE_AFTER_CLOSE_TAG_NAME,
61   STATE_INSIDE_PASSTHROUGH,
62   STATE_ERROR
63 } GMarkupParseState;
64
65 typedef struct
66 {
67   const char *prev_element;
68   const GMarkupParser *prev_parser;
69   gpointer prev_user_data;
70 } GMarkupRecursionTracker;
71
72 struct _GMarkupParseContext
73 {
74   const GMarkupParser *parser;
75
76   GMarkupParseFlags flags;
77
78   gint line_number;
79   gint char_number;
80
81   gpointer user_data;
82   GDestroyNotify dnotify;
83
84   /* A piece of character data or an element that
85    * hasn't "ended" yet so we haven't yet called
86    * the callback for it.
87    */
88   GString *partial_chunk;
89   GSList *spare_chunks;
90
91   GMarkupParseState state;
92   GSList *tag_stack;
93   GSList *tag_stack_gstr;
94   GSList *spare_list_nodes;
95
96   GString **attr_names;
97   GString **attr_values;
98   gint cur_attr;
99   gint alloc_attrs;
100
101   const gchar *current_text;
102   gssize       current_text_len;      
103   const gchar *current_text_end;
104
105   /* used to save the start of the last interesting thingy */
106   const gchar *start;
107
108   const gchar *iter;
109
110   guint document_empty : 1;
111   guint parsing : 1;
112   guint awaiting_pop : 1;
113   gint balance;
114
115   /* subparser support */
116   GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
117   const char *subparser_element;
118   gpointer held_user_data;
119 };
120
121 /*
122  * Helpers to reduce our allocation overhead, we have
123  * a well defined allocation lifecycle.
124  */
125 static GSList *
126 get_list_node (GMarkupParseContext *context, gpointer data)
127 {
128   GSList *node;
129   if (context->spare_list_nodes != NULL)
130     {
131       node = context->spare_list_nodes;
132       context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
133     }
134   else
135     node = g_slist_alloc();
136   node->data = data;
137   return node;
138 }
139
140 static void
141 free_list_node (GMarkupParseContext *context, GSList *node)
142 {
143   node->data = NULL;
144   context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
145 }
146
147 static inline void
148 string_blank (GString *string)
149 {
150   string->str[0] = '\0';
151   string->len = 0;
152 }
153
154 /**
155  * g_markup_parse_context_new:
156  * @parser: a #GMarkupParser
157  * @flags: one or more #GMarkupParseFlags
158  * @user_data: user data to pass to #GMarkupParser functions
159  * @user_data_dnotify: user data destroy notifier called when the parse context is freed
160  * 
161  * Creates a new parse context. A parse context is used to parse
162  * marked-up documents. You can feed any number of documents into
163  * a context, as long as no errors occur; once an error occurs,
164  * the parse context can't continue to parse text (you have to free it
165  * and create a new parse context).
166  * 
167  * Return value: a new #GMarkupParseContext
168  **/
169 GMarkupParseContext *
170 g_markup_parse_context_new (const GMarkupParser *parser,
171                             GMarkupParseFlags    flags,
172                             gpointer             user_data,
173                             GDestroyNotify       user_data_dnotify)
174 {
175   GMarkupParseContext *context;
176
177   g_return_val_if_fail (parser != NULL, NULL);
178
179   context = g_new (GMarkupParseContext, 1);
180
181   context->parser = parser;
182   context->flags = flags;
183   context->user_data = user_data;
184   context->dnotify = user_data_dnotify;
185
186   context->line_number = 1;
187   context->char_number = 1;
188
189   context->partial_chunk = NULL;
190   context->spare_chunks = NULL;
191   context->spare_list_nodes = NULL;
192
193   context->state = STATE_START;
194   context->tag_stack = NULL;
195   context->tag_stack_gstr = NULL;
196   context->attr_names = NULL;
197   context->attr_values = NULL;
198   context->cur_attr = -1;
199   context->alloc_attrs = 0;
200
201   context->current_text = NULL;
202   context->current_text_len = -1;
203   context->current_text_end = NULL;
204
205   context->start = NULL;
206   context->iter = NULL;
207
208   context->document_empty = TRUE;
209   context->parsing = FALSE;
210
211   context->awaiting_pop = FALSE;
212   context->subparser_stack = NULL;
213   context->subparser_element = NULL;
214
215   /* this is only looked at if awaiting_pop = TRUE.  initialise anyway. */
216   context->held_user_data = NULL;
217
218   context->balance = 0;
219
220   return context;
221 }
222
223 static void
224 string_full_free (gpointer ptr, gpointer user_data)
225 {
226   g_string_free (ptr, TRUE);
227 }
228
229 static void clear_attributes (GMarkupParseContext *context);
230
231 /**
232  * g_markup_parse_context_free:
233  * @context: a #GMarkupParseContext
234  * 
235  * Frees a #GMarkupParseContext. Can't be called from inside
236  * one of the #GMarkupParser functions. Can't be called while
237  * a subparser is pushed.
238  **/
239 void
240 g_markup_parse_context_free (GMarkupParseContext *context)
241 {
242   g_return_if_fail (context != NULL);
243   g_return_if_fail (!context->parsing);
244   g_return_if_fail (!context->subparser_stack);
245   g_return_if_fail (!context->awaiting_pop);
246
247   if (context->dnotify)
248     (* context->dnotify) (context->user_data);
249
250   clear_attributes (context);
251   g_free (context->attr_names);
252   g_free (context->attr_values);
253
254   g_slist_foreach (context->tag_stack_gstr, string_full_free, NULL);
255   g_slist_free (context->tag_stack_gstr);
256   g_slist_free (context->tag_stack);
257
258   g_slist_foreach (context->spare_chunks, string_full_free, NULL);
259   g_slist_free (context->spare_chunks);
260   g_slist_free (context->spare_list_nodes);
261
262   if (context->partial_chunk)
263     g_string_free (context->partial_chunk, TRUE);
264
265   g_free (context);
266 }
267
268 static void pop_subparser_stack (GMarkupParseContext *context);
269
270 static void
271 mark_error (GMarkupParseContext *context,
272             GError              *error)
273 {
274   context->state = STATE_ERROR;
275
276   if (context->parser->error)
277     (*context->parser->error) (context, error, context->user_data);
278
279   /* report the error all the way up to free all the user-data */
280   while (context->subparser_stack)
281     {
282       pop_subparser_stack (context);
283       context->awaiting_pop = FALSE; /* already been freed */
284
285       if (context->parser->error)
286         (*context->parser->error) (context, error, context->user_data);
287     }
288 }
289
290 static void set_error (GMarkupParseContext *context,
291                        GError             **error,
292                        GMarkupError         code,
293                        const gchar         *format,
294                        ...) G_GNUC_PRINTF (4, 5);
295
296 static void
297 set_error_literal (GMarkupParseContext *context,
298                    GError             **error,
299                    GMarkupError         code,
300                    const gchar         *message)
301 {
302   GError *tmp_error;
303
304   tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
305
306   g_prefix_error (&tmp_error,
307                   _("Error on line %d char %d: "),
308                   context->line_number,
309                   context->char_number);
310
311   mark_error (context, tmp_error);
312
313   g_propagate_error (error, tmp_error);
314 }
315
316 static void
317 set_error (GMarkupParseContext *context,
318            GError             **error,
319            GMarkupError         code,
320            const gchar         *format,
321            ...)
322 {
323   gchar *s;
324   gchar *s_valid;
325   va_list args;
326
327   va_start (args, format);
328   s = g_strdup_vprintf (format, args);
329   va_end (args);
330
331   /* Make sure that the GError message is valid UTF-8 even if it is
332    * complaining about invalid UTF-8 in the markup: */
333   s_valid = _g_utf8_make_valid (s);
334   set_error_literal (context, error, code, s);
335
336   g_free (s);
337   g_free (s_valid);
338 }
339
340 static void
341 propagate_error (GMarkupParseContext  *context,
342                  GError              **dest,
343                  GError               *src)
344 {
345   if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
346     g_prefix_error (&src,
347                     _("Error on line %d char %d: "),
348                     context->line_number,
349                     context->char_number);
350
351   mark_error (context, src);
352
353   g_propagate_error (dest, src);
354 }
355
356 #define IS_COMMON_NAME_END_CHAR(c) \
357   ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
358
359 static gboolean
360 slow_name_validate (GMarkupParseContext *context, const char *name, GError **error)
361 {
362   const char *p = name;
363
364   if (!g_utf8_validate (name, strlen (name), NULL))
365     {
366       set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
367                  _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
368       return FALSE;
369     }
370
371   if (!(g_ascii_isalpha (*p) ||
372         (!IS_COMMON_NAME_END_CHAR (*p) &&
373          (*p == '_' || 
374           *p == ':' ||
375           g_unichar_isalpha (g_utf8_get_char (p))))))
376     {
377       set_error (context, error, G_MARKUP_ERROR_PARSE,
378                  _("'%s' is not a valid name "), name);
379       return FALSE;
380     }
381
382   for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
383     {
384       /* is_name_char */
385       if (!(g_ascii_isalnum (*p) ||
386             (!IS_COMMON_NAME_END_CHAR (*p) &&
387              (*p == '.' || 
388               *p == '-' ||
389               *p == '_' ||
390               *p == ':' ||
391               g_unichar_isalpha (g_utf8_get_char (p))))))
392         {
393           set_error (context, error, G_MARKUP_ERROR_PARSE,
394                      _("'%s' is not a valid name: '%c' "), name, *p);
395           return FALSE;
396         }
397     }
398   return TRUE;
399 }
400
401 /* 
402  * Use me for elements, attributes etc.
403  */
404 static gboolean
405 name_validate (GMarkupParseContext *context, const char *name, GError **error)
406 {
407   char mask;
408   const char *p;
409
410   /* name start char */
411   p = name;
412   if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
413                   !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
414     goto slow_validate;
415   
416   for (mask = *p++; *p != '\0'; p++)
417     {
418       mask |= *p;
419
420       /* is_name_char */
421       if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
422                         (!IS_COMMON_NAME_END_CHAR (*p) &&
423                          (*p == '.' || 
424                           *p == '-' ||
425                           *p == '_' ||
426                           *p == ':')))))
427         goto slow_validate;
428     }
429
430   if (mask & 0x80) /* un-common / non-ascii */
431     goto slow_validate;
432
433   return TRUE;
434
435  slow_validate:
436   return slow_name_validate (context, name, error);
437 }
438
439 static gboolean
440 text_validate (GMarkupParseContext *context, const char *p, int len, GError **error)
441 {
442   if (!g_utf8_validate (p, len, NULL))
443     {
444       set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
445                  _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
446       return FALSE;
447     }
448   else
449     return TRUE;
450 }
451
452 static gchar*
453 char_str (gunichar c,
454           gchar   *buf)
455 {
456   memset (buf, 0, 8);
457   g_unichar_to_utf8 (c, buf);
458   return buf;
459 }
460
461 static gchar*
462 utf8_str (const gchar *utf8,
463           gchar       *buf)
464 {
465   char_str (g_utf8_get_char (utf8), buf);
466   return buf;
467 }
468
469 static void
470 set_unescape_error (GMarkupParseContext *context,
471                     GError             **error,
472                     const gchar         *remaining_text,
473                     GMarkupError         code,
474                     const gchar         *format,
475                     ...)
476 {
477   GError *tmp_error;
478   gchar *s;
479   va_list args;
480   gint remaining_newlines;
481   const gchar *p;
482
483   remaining_newlines = 0;
484   p = remaining_text;
485   while (*p != '\0')
486     {
487       if (*p == '\n')
488         ++remaining_newlines;
489       ++p;
490     }
491
492   va_start (args, format);
493   s = g_strdup_vprintf (format, args);
494   va_end (args);
495
496   tmp_error = g_error_new (G_MARKUP_ERROR,
497                            code,
498                            _("Error on line %d: %s"),
499                            context->line_number - remaining_newlines,
500                            s);
501
502   g_free (s);
503
504   mark_error (context, tmp_error);
505
506   g_propagate_error (error, tmp_error);
507 }
508
509 /*
510  * re-write the GString in-place, unescaping anything that escaped.
511  * most XML does not contain entities, or escaping.
512  */
513 static gboolean
514 unescape_gstring_inplace (GMarkupParseContext *context,
515                           GString             *string,
516                           gboolean            *is_ascii,
517                           GError             **error)
518 {
519   char mask, *to;
520   int line_num = 1;
521   const char *from;
522   gboolean normalize_attribute;
523
524   *is_ascii = FALSE;
525
526   /* are we unescaping an attribute or not ? */
527   if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
528       context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
529     normalize_attribute = TRUE;
530   else
531     normalize_attribute = FALSE;
532
533   /*
534    * Meeks' theorum: unescaping can only shrink text.
535    * for &lt; etc. this is obvious, for &#xffff; more
536    * thought is required, but this is patently so.
537    */
538   mask = 0;
539   for (from = to = string->str; *from != '\0'; from++, to++) 
540     {
541       *to = *from;
542
543       mask |= *to;
544       if (*to == '\n')
545         line_num++;
546       if (normalize_attribute && (*to == '\t' || *to == '\n'))
547         *to = ' ';
548       if (*to == '\r')
549         {
550           *to = normalize_attribute ? ' ' : '\n';
551           if (from[1] == '\n')
552             from++;
553         }
554       if (*from == '&')
555         {
556           from++;
557           if (*from == '#')
558             {
559               gboolean is_hex = FALSE;
560               gulong l;
561               gchar *end = NULL;
562
563               from++;
564
565               if (*from == 'x')
566                 {
567                   is_hex = TRUE;
568                   from++;
569                 }
570
571               /* digit is between start and p */
572               errno = 0;
573               if (is_hex)
574                 l = strtoul (from, &end, 16);
575               else
576                 l = strtoul (from, &end, 10);
577               
578               if (end == from || errno != 0)
579                 {
580                   set_unescape_error (context, error,
581                                       from, G_MARKUP_ERROR_PARSE,
582                                       _("Failed to parse '%-.*s', which "
583                                         "should have been a digit "
584                                         "inside a character reference "
585                                         "(&#234; for example) - perhaps "
586                                         "the digit is too large"),
587                                       end - from, from);
588                   return FALSE;
589                 }
590               else if (*end != ';')
591                 {
592                   set_unescape_error (context, error,
593                                       from, G_MARKUP_ERROR_PARSE,
594                                       _("Character reference did not end with a "
595                                         "semicolon; "
596                                         "most likely you used an ampersand "
597                                         "character without intending to start "
598                                         "an entity - escape ampersand as &amp;"));
599                   return FALSE;
600                 }
601               else
602                 {
603                   /* characters XML 1.1 permits */
604                   if ((0 < l && l <= 0xD7FF) ||
605                       (0xE000 <= l && l <= 0xFFFD) ||
606                       (0x10000 <= l && l <= 0x10FFFF))
607                     {
608                       gchar buf[8];
609                       char_str (l, buf);
610                       strcpy (to, buf);
611                       to += strlen (buf) - 1;
612                       from = end;
613                       if (l >= 0x80) /* not ascii */
614                         mask |= 0x80;
615                     }
616                   else
617                     {
618                       set_unescape_error (context, error,
619                                           from, G_MARKUP_ERROR_PARSE,
620                                           _("Character reference '%-.*s' does not "
621                                             "encode a permitted character"),
622                                           end - from, from);
623                       return FALSE;
624                     }
625                 }
626             }
627
628           else if (strncmp (from, "lt;", 3) == 0)
629             {
630               *to = '<';
631               from += 2;
632             }
633           else if (strncmp (from, "gt;", 3) == 0)
634             {
635               *to = '>';
636               from += 2;
637             }
638           else if (strncmp (from, "amp;", 4) == 0)
639             {
640               *to = '&';
641               from += 3;
642             }
643           else if (strncmp (from, "quot;", 5) == 0)
644             {
645               *to = '"';
646               from += 4;
647             }
648           else if (strncmp (from, "apos;", 5) == 0)
649             {
650               *to = '\'';
651               from += 4;
652             }
653           else
654             {
655               if (*from == ';')
656                 set_unescape_error (context, error,
657                                     from, G_MARKUP_ERROR_PARSE,
658                                     _("Empty entity '&;' seen; valid "
659                                       "entities are: &amp; &quot; &lt; &gt; &apos;"));
660               else
661                 {
662                   const char *end = strchr (from, ';');
663                   if (end)
664                     set_unescape_error (context, error,
665                                         from, G_MARKUP_ERROR_PARSE,
666                                         _("Entity name '%-.*s' is not known"),
667                                         end-from, from);
668                   else
669                     set_unescape_error (context, error,
670                                         from, G_MARKUP_ERROR_PARSE,
671                                         _("Entity did not end with a semicolon; "
672                                           "most likely you used an ampersand "
673                                           "character without intending to start "
674                                           "an entity - escape ampersand as &amp;"));
675                 }
676               return FALSE;
677             }
678         }
679     }
680
681   g_assert (to - string->str <= string->len);
682   if (to - string->str != string->len)
683     g_string_truncate (string, to - string->str);
684
685   *is_ascii = !(mask & 0x80);
686
687   return TRUE;
688 }
689
690 static inline gboolean
691 advance_char (GMarkupParseContext *context)
692 {  
693   context->iter++;
694   context->char_number++;
695
696   if (G_UNLIKELY (context->iter == context->current_text_end))
697       return FALSE;
698
699   else if (G_UNLIKELY (*context->iter == '\n'))
700     {
701       context->line_number++;
702       context->char_number = 1;
703     }
704   
705   return TRUE;
706 }
707
708 static inline gboolean
709 xml_isspace (char c)
710 {
711   return c == ' ' || c == '\t' || c == '\n' || c == '\r';
712 }
713
714 static void
715 skip_spaces (GMarkupParseContext *context)
716 {
717   do
718     {
719       if (!xml_isspace (*context->iter))
720         return;
721     }
722   while (advance_char (context));
723 }
724
725 static void
726 advance_to_name_end (GMarkupParseContext *context)
727 {
728   do
729     {
730       if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
731         return;
732       if (xml_isspace (*(context->iter)))
733         return;
734     }
735   while (advance_char (context));
736 }
737
738 static void
739 release_chunk (GMarkupParseContext *context, GString *str)
740 {
741   GSList *node;
742   if (!str)
743     return;
744   if (str->allocated_len > 256)
745     { /* large strings are unusual and worth freeing */
746       g_string_free (str, TRUE);
747       return;
748     }
749   string_blank (str);
750   node = get_list_node (context, str);
751   context->spare_chunks = g_slist_concat (node, context->spare_chunks);
752 }
753
754 static void
755 add_to_partial (GMarkupParseContext *context,
756                 const gchar         *text_start,
757                 const gchar         *text_end)
758 {
759   if (context->partial_chunk == NULL)
760     { /* allocate a new chunk to parse into */
761
762       if (context->spare_chunks != NULL)
763         {
764           GSList *node = context->spare_chunks;
765           context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
766           context->partial_chunk = node->data;
767           free_list_node (context, node);
768         }
769       else
770         context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
771     }
772
773   if (text_start != text_end)
774     g_string_insert_len (context->partial_chunk, -1,
775                          text_start, text_end - text_start);
776 }
777
778 static inline void
779 truncate_partial (GMarkupParseContext *context)
780 {
781   if (context->partial_chunk != NULL)
782     string_blank (context->partial_chunk);
783 }
784
785 static inline const gchar*
786 current_element (GMarkupParseContext *context)
787 {
788   return context->tag_stack->data;
789 }
790
791 static void
792 pop_subparser_stack (GMarkupParseContext *context)
793 {
794   GMarkupRecursionTracker *tracker;
795
796   g_assert (context->subparser_stack);
797
798   tracker = context->subparser_stack->data;
799
800   context->awaiting_pop = TRUE;
801   context->held_user_data = context->user_data;
802
803   context->user_data = tracker->prev_user_data;
804   context->parser = tracker->prev_parser;
805   context->subparser_element = tracker->prev_element;
806   g_slice_free (GMarkupRecursionTracker, tracker);
807
808   context->subparser_stack = g_slist_delete_link (context->subparser_stack,
809                                                   context->subparser_stack);
810 }
811
812 static void
813 push_partial_as_tag (GMarkupParseContext *context)
814 {
815   GString *str = context->partial_chunk;
816   /* sadly, this is exported by gmarkup_get_element_stack as-is */
817   context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
818   context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
819   context->partial_chunk = NULL;
820 }
821
822 static void
823 pop_tag (GMarkupParseContext *context)
824 {
825   GSList *nodea, *nodeb;
826
827   nodea = context->tag_stack;
828   nodeb = context->tag_stack_gstr;
829   release_chunk (context, nodeb->data);
830   context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
831   context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
832   free_list_node (context, nodea);
833   free_list_node (context, nodeb);
834 }
835
836 static void
837 possibly_finish_subparser (GMarkupParseContext *context)
838 {
839   if (current_element (context) == context->subparser_element)
840     pop_subparser_stack (context);
841 }
842
843 static void
844 ensure_no_outstanding_subparser (GMarkupParseContext *context)
845 {
846   if (context->awaiting_pop)
847     g_critical ("During the first end_element call after invoking a "
848                 "subparser you must pop the subparser stack and handle "
849                 "the freeing of the subparser user_data.  This can be "
850                 "done by calling the end function of the subparser.  "
851                 "Very probably, your program just leaked memory.");
852
853   /* let valgrind watch the pointer disappear... */
854   context->held_user_data = NULL;
855   context->awaiting_pop = FALSE;
856 }
857
858 static const gchar*
859 current_attribute (GMarkupParseContext *context)
860 {
861   g_assert (context->cur_attr >= 0);
862   return context->attr_names[context->cur_attr]->str;
863 }
864
865 static void
866 add_attribute (GMarkupParseContext *context, GString *str)
867 {
868   if (context->cur_attr + 2 >= context->alloc_attrs)
869     {
870       context->alloc_attrs += 5; /* silly magic number */
871       context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
872       context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
873     }
874   context->cur_attr++;
875   context->attr_names[context->cur_attr] = str;
876   context->attr_values[context->cur_attr] = NULL;
877   context->attr_names[context->cur_attr+1] = NULL;
878   context->attr_values[context->cur_attr+1] = NULL;
879 }
880
881 static void
882 clear_attributes (GMarkupParseContext *context)
883 {
884   /* Go ahead and free the attributes. */
885   for (; context->cur_attr >= 0; context->cur_attr--)
886     {
887       int pos = context->cur_attr;
888       release_chunk (context, context->attr_names[pos]);
889       release_chunk (context, context->attr_values[pos]);
890       context->attr_names[pos] = context->attr_values[pos] = NULL;
891     }
892   g_assert (context->cur_attr == -1);
893   g_assert (context->attr_names == NULL ||
894             context->attr_names[0] == NULL);
895   g_assert (context->attr_values == NULL ||
896             context->attr_values[0] == NULL);
897 }
898
899 /* This has to be a separate function to ensure the alloca's
900    are unwound on exit - otherwise we grow & blow the stack
901    with large documents */
902 static inline void
903 emit_start_element (GMarkupParseContext *context, GError **error)
904 {
905   int i;
906   const gchar *start_name;
907   const gchar **attr_names;
908   const gchar **attr_values;
909   GError *tmp_error;
910   
911   attr_names = g_newa (const gchar *, context->cur_attr + 2);
912   attr_values = g_newa (const gchar *, context->cur_attr + 2);
913   for (i = 0; i < context->cur_attr + 1; i++)
914     {
915       attr_names[i] = context->attr_names[i]->str;
916       attr_values[i] = context->attr_values[i]->str;
917     }
918   attr_names[i] = NULL;
919   attr_values[i] = NULL;
920   
921   /* Call user callback for element start */
922   tmp_error = NULL;
923   start_name = current_element (context);
924   
925   if (context->parser->start_element &&
926       name_validate (context, start_name, error))
927     (* context->parser->start_element) (context,
928                                         start_name,
929                                         (const gchar **)attr_names,
930                                         (const gchar **)attr_values,
931                                         context->user_data,
932                                         &tmp_error);
933   clear_attributes (context);
934   
935   if (tmp_error != NULL)
936     propagate_error (context, error, tmp_error);
937 }
938
939 /**
940  * g_markup_parse_context_parse:
941  * @context: a #GMarkupParseContext
942  * @text: chunk of text to parse
943  * @text_len: length of @text in bytes
944  * @error: return location for a #GError
945  * 
946  * Feed some data to the #GMarkupParseContext. The data need not
947  * be valid UTF-8; an error will be signaled if it's invalid.
948  * The data need not be an entire document; you can feed a document
949  * into the parser incrementally, via multiple calls to this function.
950  * Typically, as you receive data from a network connection or file,
951  * you feed each received chunk of data into this function, aborting
952  * the process if an error occurs. Once an error is reported, no further
953  * data may be fed to the #GMarkupParseContext; all errors are fatal.
954  * 
955  * Return value: %FALSE if an error occurred, %TRUE on success
956  **/
957 gboolean
958 g_markup_parse_context_parse (GMarkupParseContext *context,
959                               const gchar         *text,
960                               gssize               text_len,
961                               GError             **error)
962 {
963   g_return_val_if_fail (context != NULL, FALSE);
964   g_return_val_if_fail (text != NULL, FALSE);
965   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
966   g_return_val_if_fail (!context->parsing, FALSE);
967   
968   if (text_len < 0)
969     text_len = strlen (text);
970
971   if (text_len == 0)
972     return TRUE;
973   
974   context->parsing = TRUE;
975   
976
977   context->current_text = text;
978   context->current_text_len = text_len;
979   context->current_text_end = context->current_text + text_len;
980   context->iter = context->current_text;
981   context->start = context->iter;
982
983   if (context->current_text_len == 0)
984     goto finished;
985
986   while (context->iter != context->current_text_end)
987     {
988       switch (context->state)
989         {
990         case STATE_START:
991           /* Possible next state: AFTER_OPEN_ANGLE */
992
993           g_assert (context->tag_stack == NULL);
994
995           /* whitespace is ignored outside of any elements */
996           skip_spaces (context);
997
998           if (context->iter != context->current_text_end)
999             {
1000               if (*context->iter == '<')
1001                 {
1002                   /* Move after the open angle */
1003                   advance_char (context);
1004
1005                   context->state = STATE_AFTER_OPEN_ANGLE;
1006
1007                   /* this could start a passthrough */
1008                   context->start = context->iter;
1009
1010                   /* document is now non-empty */
1011                   context->document_empty = FALSE;
1012                 }
1013               else
1014                 {
1015                   set_error_literal (context,
1016                                      error,
1017                                      G_MARKUP_ERROR_PARSE,
1018                                      _("Document must begin with an element (e.g. <book>)"));
1019                 }
1020             }
1021           break;
1022
1023         case STATE_AFTER_OPEN_ANGLE:
1024           /* Possible next states: INSIDE_OPEN_TAG_NAME,
1025            *  AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1026            */
1027           if (*context->iter == '?' ||
1028               *context->iter == '!')
1029             {
1030               /* include < in the passthrough */
1031               const gchar *openangle = "<";
1032               add_to_partial (context, openangle, openangle + 1);
1033               context->start = context->iter;
1034               context->balance = 1;
1035               context->state = STATE_INSIDE_PASSTHROUGH;
1036             }
1037           else if (*context->iter == '/')
1038             {
1039               /* move after it */
1040               advance_char (context);
1041
1042               context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1043             }
1044           else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1045             {
1046               context->state = STATE_INSIDE_OPEN_TAG_NAME;
1047
1048               /* start of tag name */
1049               context->start = context->iter;
1050             }
1051           else
1052             {
1053               gchar buf[8];
1054
1055               set_error (context,
1056                          error,
1057                          G_MARKUP_ERROR_PARSE,
1058                          _("'%s' is not a valid character following "
1059                            "a '<' character; it may not begin an "
1060                            "element name"),
1061                          utf8_str (context->iter, buf));
1062             }
1063           break;
1064
1065           /* The AFTER_CLOSE_ANGLE state is actually sort of
1066            * broken, because it doesn't correspond to a range
1067            * of characters in the input stream as the others do,
1068            * and thus makes things harder to conceptualize
1069            */
1070         case STATE_AFTER_CLOSE_ANGLE:
1071           /* Possible next states: INSIDE_TEXT, STATE_START */
1072           if (context->tag_stack == NULL)
1073             {
1074               context->start = NULL;
1075               context->state = STATE_START;
1076             }
1077           else
1078             {
1079               context->start = context->iter;
1080               context->state = STATE_INSIDE_TEXT;
1081             }
1082           break;
1083
1084         case STATE_AFTER_ELISION_SLASH:
1085           /* Possible next state: AFTER_CLOSE_ANGLE */
1086
1087           {
1088             /* We need to pop the tag stack and call the end_element
1089              * function, since this is the close tag
1090              */
1091             GError *tmp_error = NULL;
1092           
1093             g_assert (context->tag_stack != NULL);
1094
1095             possibly_finish_subparser (context);
1096
1097             tmp_error = NULL;
1098             if (context->parser->end_element)
1099               (* context->parser->end_element) (context,
1100                                                 current_element (context),
1101                                                 context->user_data,
1102                                                 &tmp_error);
1103
1104             ensure_no_outstanding_subparser (context);
1105           
1106             if (tmp_error)
1107               {
1108                 mark_error (context, tmp_error);
1109                 g_propagate_error (error, tmp_error);
1110               }          
1111             else
1112               {
1113                 if (*context->iter == '>')
1114                   {
1115                     /* move after the close angle */
1116                     advance_char (context);
1117                     context->state = STATE_AFTER_CLOSE_ANGLE;
1118                   }
1119                 else
1120                   {
1121                     gchar buf[8];
1122
1123                     set_error (context,
1124                                error,
1125                                G_MARKUP_ERROR_PARSE,
1126                                _("Odd character '%s', expected a '>' character "
1127                                  "to end the empty-element tag '%s'"),
1128                                utf8_str (context->iter, buf),
1129                                current_element (context));
1130                   }
1131               }
1132             pop_tag (context);
1133           }
1134           break;
1135
1136         case STATE_INSIDE_OPEN_TAG_NAME:
1137           /* Possible next states: BETWEEN_ATTRIBUTES */
1138
1139           /* if there's a partial chunk then it's the first part of the
1140            * tag name. If there's a context->start then it's the start
1141            * of the tag name in current_text, the partial chunk goes
1142            * before that start though.
1143            */
1144           advance_to_name_end (context);
1145
1146           if (context->iter == context->current_text_end)
1147             {
1148               /* The name hasn't necessarily ended. Merge with
1149                * partial chunk, leave state unchanged.
1150                */
1151               add_to_partial (context, context->start, context->iter);
1152             }
1153           else
1154             {
1155               /* The name has ended. Combine it with the partial chunk
1156                * if any; push it on the stack; enter next state.
1157                */
1158               add_to_partial (context, context->start, context->iter);
1159               push_partial_as_tag (context);
1160
1161               context->state = STATE_BETWEEN_ATTRIBUTES;
1162               context->start = NULL;
1163             }
1164           break;
1165
1166         case STATE_INSIDE_ATTRIBUTE_NAME:
1167           /* Possible next states: AFTER_ATTRIBUTE_NAME */
1168
1169           advance_to_name_end (context);
1170           add_to_partial (context, context->start, context->iter);
1171
1172           /* read the full name, if we enter the equals sign state
1173            * then add the attribute to the list (without the value),
1174            * otherwise store a partial chunk to be prepended later.
1175            */
1176           if (context->iter != context->current_text_end)
1177             context->state = STATE_AFTER_ATTRIBUTE_NAME;
1178           break;
1179
1180         case STATE_AFTER_ATTRIBUTE_NAME:
1181           /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1182
1183           skip_spaces (context);
1184
1185           if (context->iter != context->current_text_end)
1186             {
1187               /* The name has ended. Combine it with the partial chunk
1188                * if any; push it on the stack; enter next state.
1189                */
1190               if (!name_validate (context, context->partial_chunk->str, error))
1191                 break;
1192
1193               add_attribute (context, context->partial_chunk);
1194               
1195               context->partial_chunk = NULL;
1196               context->start = NULL;
1197               
1198               if (*context->iter == '=')
1199                 {
1200                   advance_char (context);
1201                   context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1202                 }
1203               else
1204                 {
1205                   gchar buf[8];
1206
1207                   set_error (context,
1208                              error,
1209                              G_MARKUP_ERROR_PARSE,
1210                              _("Odd character '%s', expected a '=' after "
1211                                "attribute name '%s' of element '%s'"),
1212                              utf8_str (context->iter, buf),
1213                              current_attribute (context),
1214                              current_element (context));
1215                   
1216                 }
1217             }
1218           break;
1219
1220         case STATE_BETWEEN_ATTRIBUTES:
1221           /* Possible next states: AFTER_CLOSE_ANGLE,
1222            * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1223            */
1224           skip_spaces (context);
1225
1226           if (context->iter != context->current_text_end)
1227             {
1228               if (*context->iter == '/')
1229                 {
1230                   advance_char (context);
1231                   context->state = STATE_AFTER_ELISION_SLASH;
1232                 }
1233               else if (*context->iter == '>')
1234                 {
1235                   advance_char (context);
1236                   context->state = STATE_AFTER_CLOSE_ANGLE;
1237                 }
1238               else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1239                 {
1240                   context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1241                   /* start of attribute name */
1242                   context->start = context->iter;
1243                 }
1244               else
1245                 {
1246                   gchar buf[8];
1247
1248                   set_error (context,
1249                              error,
1250                              G_MARKUP_ERROR_PARSE,
1251                              _("Odd character '%s', expected a '>' or '/' "
1252                                "character to end the start tag of "
1253                                "element '%s', or optionally an attribute; "
1254                                "perhaps you used an invalid character in "
1255                                "an attribute name"),
1256                              utf8_str (context->iter, buf),
1257                              current_element (context));
1258                 }
1259
1260               /* If we're done with attributes, invoke
1261                * the start_element callback
1262                */
1263               if (context->state == STATE_AFTER_ELISION_SLASH ||
1264                   context->state == STATE_AFTER_CLOSE_ANGLE)
1265                 emit_start_element (context, error);
1266             }
1267           break;
1268
1269         case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1270           /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1271
1272           skip_spaces (context);
1273
1274           if (context->iter != context->current_text_end)
1275             {
1276               if (*context->iter == '"')
1277                 {
1278                   advance_char (context);
1279                   context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1280                   context->start = context->iter;
1281                 }
1282               else if (*context->iter == '\'')
1283                 {
1284                   advance_char (context);
1285                   context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1286                   context->start = context->iter;
1287                 }
1288               else
1289                 {
1290                   gchar buf[8];
1291                   
1292                   set_error (context,
1293                              error,
1294                              G_MARKUP_ERROR_PARSE,
1295                              _("Odd character '%s', expected an open quote mark "
1296                                "after the equals sign when giving value for "
1297                                "attribute '%s' of element '%s'"),
1298                              utf8_str (context->iter, buf),
1299                              current_attribute (context),
1300                              current_element (context));
1301                 }
1302             }
1303           break;
1304
1305         case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1306         case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1307           /* Possible next states: BETWEEN_ATTRIBUTES */
1308           {
1309             gchar delim;
1310
1311             if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ) 
1312               {
1313                 delim = '\'';
1314               }
1315             else 
1316               {
1317                 delim = '"';
1318               }
1319
1320             do
1321               {
1322                 if (*context->iter == delim)
1323                   break;
1324               }
1325             while (advance_char (context));
1326           }
1327           if (context->iter == context->current_text_end)
1328             {
1329               /* The value hasn't necessarily ended. Merge with
1330                * partial chunk, leave state unchanged.
1331                */
1332               add_to_partial (context, context->start, context->iter);
1333             }
1334           else
1335             {
1336               gboolean is_ascii;
1337               /* The value has ended at the quote mark. Combine it
1338                * with the partial chunk if any; set it for the current
1339                * attribute.
1340                */
1341               add_to_partial (context, context->start, context->iter);
1342
1343               g_assert (context->cur_attr >= 0);
1344               
1345               if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1346                   (is_ascii || text_validate (context, context->partial_chunk->str,
1347                                               context->partial_chunk->len, error)))
1348                 {
1349                   /* success, advance past quote and set state. */
1350                   context->attr_values[context->cur_attr] = context->partial_chunk;
1351                   context->partial_chunk = NULL;
1352                   advance_char (context);
1353                   context->state = STATE_BETWEEN_ATTRIBUTES;
1354                   context->start = NULL;
1355                 }
1356               
1357               truncate_partial (context);
1358             }
1359           break;
1360
1361         case STATE_INSIDE_TEXT:
1362           /* Possible next states: AFTER_OPEN_ANGLE */
1363           do
1364             {
1365               if (*context->iter == '<')
1366                 break;
1367             }
1368           while (advance_char (context));
1369
1370           /* The text hasn't necessarily ended. Merge with
1371            * partial chunk, leave state unchanged.
1372            */
1373
1374           add_to_partial (context, context->start, context->iter);
1375
1376           if (context->iter != context->current_text_end)
1377             {
1378               gboolean is_ascii;
1379
1380               /* The text has ended at the open angle. Call the text
1381                * callback.
1382                */
1383               
1384               if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1385                   (is_ascii || text_validate (context, context->partial_chunk->str,
1386                                               context->partial_chunk->len, error)))
1387                 {
1388                   GError *tmp_error = NULL;
1389
1390                   if (context->parser->text)
1391                     (*context->parser->text) (context,
1392                                               context->partial_chunk->str,
1393                                               context->partial_chunk->len,
1394                                               context->user_data,
1395                                               &tmp_error);
1396                   
1397                   if (tmp_error == NULL)
1398                     {
1399                       /* advance past open angle and set state. */
1400                       advance_char (context);
1401                       context->state = STATE_AFTER_OPEN_ANGLE;
1402                       /* could begin a passthrough */
1403                       context->start = context->iter;
1404                     }
1405                   else
1406                     propagate_error (context, error, tmp_error);
1407                 }
1408
1409               truncate_partial (context);
1410             }
1411           break;
1412
1413         case STATE_AFTER_CLOSE_TAG_SLASH:
1414           /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1415           if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1416             {
1417               context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1418
1419               /* start of tag name */
1420               context->start = context->iter;
1421             }
1422           else
1423             {
1424               gchar buf[8];
1425
1426               set_error (context,
1427                          error,
1428                          G_MARKUP_ERROR_PARSE,
1429                          _("'%s' is not a valid character following "
1430                            "the characters '</'; '%s' may not begin an "
1431                            "element name"),
1432                          utf8_str (context->iter, buf),
1433                          utf8_str (context->iter, buf));
1434             }
1435           break;
1436
1437         case STATE_INSIDE_CLOSE_TAG_NAME:
1438           /* Possible next state: AFTER_CLOSE_TAG_NAME */
1439           advance_to_name_end (context);
1440           add_to_partial (context, context->start, context->iter);
1441
1442           if (context->iter != context->current_text_end)
1443             context->state = STATE_AFTER_CLOSE_TAG_NAME;
1444           break;
1445
1446         case STATE_AFTER_CLOSE_TAG_NAME:
1447           /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1448
1449           skip_spaces (context);
1450           
1451           if (context->iter != context->current_text_end)
1452             {
1453               GString *close_name;
1454
1455               close_name = context->partial_chunk;
1456               context->partial_chunk = NULL;
1457               
1458               if (*context->iter != '>')
1459                 {
1460                   gchar buf[8];
1461
1462                   set_error (context,
1463                              error,
1464                              G_MARKUP_ERROR_PARSE,
1465                              _("'%s' is not a valid character following "
1466                                "the close element name '%s'; the allowed "
1467                                "character is '>'"),
1468                              utf8_str (context->iter, buf),
1469                              close_name->str);
1470                 }
1471               else if (context->tag_stack == NULL)
1472                 {
1473                   set_error (context,
1474                              error,
1475                              G_MARKUP_ERROR_PARSE,
1476                              _("Element '%s' was closed, no element "
1477                                "is currently open"),
1478                              close_name->str);
1479                 }
1480               else if (strcmp (close_name->str, current_element (context)) != 0)
1481                 {
1482                   set_error (context,
1483                              error,
1484                              G_MARKUP_ERROR_PARSE,
1485                              _("Element '%s' was closed, but the currently "
1486                                "open element is '%s'"),
1487                              close_name->str,
1488                              current_element (context));
1489                 }
1490               else
1491                 {
1492                   GError *tmp_error;
1493                   advance_char (context);
1494                   context->state = STATE_AFTER_CLOSE_ANGLE;
1495                   context->start = NULL;
1496                   
1497                   possibly_finish_subparser (context);
1498
1499                   /* call the end_element callback */
1500                   tmp_error = NULL;
1501                   if (context->parser->end_element)
1502                     (* context->parser->end_element) (context,
1503                                                       close_name->str,
1504                                                       context->user_data,
1505                                                       &tmp_error);
1506                   
1507                   ensure_no_outstanding_subparser (context);
1508                   pop_tag (context);
1509                   
1510                   if (tmp_error)
1511                     propagate_error (context, error, tmp_error);
1512                 }
1513               context->partial_chunk = close_name;
1514               truncate_partial (context);
1515             }
1516           break;
1517           
1518         case STATE_INSIDE_PASSTHROUGH:
1519           /* Possible next state: AFTER_CLOSE_ANGLE */
1520           do
1521             {
1522               if (*context->iter == '<') 
1523                 context->balance++;
1524               if (*context->iter == '>') 
1525                 {                               
1526                   gchar *str;
1527                   gsize len;
1528
1529                   context->balance--;
1530                   add_to_partial (context, context->start, context->iter);
1531                   context->start = context->iter;
1532
1533                   str = context->partial_chunk->str;
1534                   len = context->partial_chunk->len;
1535
1536                   if (str[1] == '?' && str[len - 1] == '?')
1537                     break;
1538                   if (strncmp (str, "<!--", 4) == 0 && 
1539                       strcmp (str + len - 2, "--") == 0)
1540                     break;
1541                   if (strncmp (str, "<![CDATA[", 9) == 0 && 
1542                       strcmp (str + len - 2, "]]") == 0)
1543                     break;
1544                   if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1545                       context->balance == 0)
1546                     break;
1547                 }
1548             }
1549           while (advance_char (context));
1550
1551           if (context->iter == context->current_text_end)
1552             {
1553               /* The passthrough hasn't necessarily ended. Merge with
1554                * partial chunk, leave state unchanged.
1555                */
1556                add_to_partial (context, context->start, context->iter);
1557             }
1558           else
1559             {
1560               /* The passthrough has ended at the close angle. Combine
1561                * it with the partial chunk if any. Call the passthrough
1562                * callback. Note that the open/close angles are
1563                * included in the text of the passthrough.
1564                */
1565               GError *tmp_error = NULL;
1566
1567               advance_char (context); /* advance past close angle */
1568               add_to_partial (context, context->start, context->iter);
1569
1570               if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1571                   strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1572                 {
1573                   if (context->parser->text &&
1574                       text_validate (context,
1575                                      context->partial_chunk->str + 9,
1576                                      context->partial_chunk->len - 12,
1577                                      error))
1578                     (*context->parser->text) (context,
1579                                               context->partial_chunk->str + 9,
1580                                               context->partial_chunk->len - 12,
1581                                               context->user_data,
1582                                               &tmp_error);
1583                 }
1584               else if (context->parser->passthrough &&
1585                        text_validate (context,
1586                                       context->partial_chunk->str,
1587                                       context->partial_chunk->len,
1588                                       error))
1589                 (*context->parser->passthrough) (context,
1590                                                  context->partial_chunk->str,
1591                                                  context->partial_chunk->len,
1592                                                  context->user_data,
1593                                                  &tmp_error);
1594                   
1595               truncate_partial (context);
1596
1597               if (tmp_error == NULL)
1598                 {
1599                   context->state = STATE_AFTER_CLOSE_ANGLE;
1600                   context->start = context->iter; /* could begin text */
1601                 }
1602               else
1603                 propagate_error (context, error, tmp_error);
1604             }
1605           break;
1606
1607         case STATE_ERROR:
1608           goto finished;
1609           break;
1610
1611         default:
1612           g_assert_not_reached ();
1613           break;
1614         }
1615     }
1616
1617  finished:
1618   context->parsing = FALSE;
1619
1620   return context->state != STATE_ERROR;
1621 }
1622
1623 /**
1624  * g_markup_parse_context_end_parse:
1625  * @context: a #GMarkupParseContext
1626  * @error: return location for a #GError
1627  * 
1628  * Signals to the #GMarkupParseContext that all data has been
1629  * fed into the parse context with g_markup_parse_context_parse().
1630  * This function reports an error if the document isn't complete,
1631  * for example if elements are still open.
1632  * 
1633  * Return value: %TRUE on success, %FALSE if an error was set
1634  **/
1635 gboolean
1636 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1637                                   GError             **error)
1638 {
1639   g_return_val_if_fail (context != NULL, FALSE);
1640   g_return_val_if_fail (!context->parsing, FALSE);
1641   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1642
1643   if (context->partial_chunk != NULL)
1644     {
1645       g_string_free (context->partial_chunk, TRUE);
1646       context->partial_chunk = NULL;
1647     }
1648
1649   if (context->document_empty)
1650     {
1651       set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1652                          _("Document was empty or contained only whitespace"));
1653       return FALSE;
1654     }
1655   
1656   context->parsing = TRUE;
1657   
1658   switch (context->state)
1659     {
1660     case STATE_START:
1661       /* Nothing to do */
1662       break;
1663
1664     case STATE_AFTER_OPEN_ANGLE:
1665       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1666                          _("Document ended unexpectedly just after an open angle bracket '<'"));
1667       break;
1668
1669     case STATE_AFTER_CLOSE_ANGLE:
1670       if (context->tag_stack != NULL)
1671         {
1672           /* Error message the same as for INSIDE_TEXT */
1673           set_error (context, error, G_MARKUP_ERROR_PARSE,
1674                      _("Document ended unexpectedly with elements still open - "
1675                        "'%s' was the last element opened"),
1676                      current_element (context));
1677         }
1678       break;
1679       
1680     case STATE_AFTER_ELISION_SLASH:
1681       set_error (context, error, G_MARKUP_ERROR_PARSE,
1682                  _("Document ended unexpectedly, expected to see a close angle "
1683                    "bracket ending the tag <%s/>"), current_element (context));
1684       break;
1685
1686     case STATE_INSIDE_OPEN_TAG_NAME:
1687       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1688                          _("Document ended unexpectedly inside an element name"));
1689       break;
1690
1691     case STATE_INSIDE_ATTRIBUTE_NAME:
1692     case STATE_AFTER_ATTRIBUTE_NAME:
1693       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1694                          _("Document ended unexpectedly inside an attribute name"));
1695       break;
1696
1697     case STATE_BETWEEN_ATTRIBUTES:
1698       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1699                          _("Document ended unexpectedly inside an element-opening "
1700                            "tag."));
1701       break;
1702
1703     case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1704       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1705                          _("Document ended unexpectedly after the equals sign "
1706                            "following an attribute name; no attribute value"));
1707       break;
1708
1709     case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1710     case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1711       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1712                          _("Document ended unexpectedly while inside an attribute "
1713                            "value"));
1714       break;
1715
1716     case STATE_INSIDE_TEXT:
1717       g_assert (context->tag_stack != NULL);
1718       set_error (context, error, G_MARKUP_ERROR_PARSE,
1719                  _("Document ended unexpectedly with elements still open - "
1720                    "'%s' was the last element opened"),
1721                  current_element (context));
1722       break;
1723
1724     case STATE_AFTER_CLOSE_TAG_SLASH:
1725     case STATE_INSIDE_CLOSE_TAG_NAME:
1726     case STATE_AFTER_CLOSE_TAG_NAME:
1727       set_error (context, error, G_MARKUP_ERROR_PARSE,
1728                  _("Document ended unexpectedly inside the close tag for "
1729                    "element '%s'"), current_element (context));
1730       break;
1731
1732     case STATE_INSIDE_PASSTHROUGH:
1733       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1734                          _("Document ended unexpectedly inside a comment or "
1735                            "processing instruction"));
1736       break;
1737
1738     case STATE_ERROR:
1739     default:
1740       g_assert_not_reached ();
1741       break;
1742     }
1743
1744   context->parsing = FALSE;
1745
1746   return context->state != STATE_ERROR;
1747 }
1748
1749 /**
1750  * g_markup_parse_context_get_element:
1751  * @context: a #GMarkupParseContext
1752  * @returns: the name of the currently open element, or %NULL
1753  *
1754  * Retrieves the name of the currently open element.
1755  *
1756  * If called from the start_element or end_element handlers this will
1757  * give the element_name as passed to those functions. For the parent
1758  * elements, see g_markup_parse_context_get_element_stack().
1759  *
1760  * Since: 2.2
1761  **/
1762 G_CONST_RETURN gchar *
1763 g_markup_parse_context_get_element (GMarkupParseContext *context)
1764 {
1765   g_return_val_if_fail (context != NULL, NULL);
1766
1767   if (context->tag_stack == NULL) 
1768     return NULL;
1769   else
1770     return current_element (context);
1771
1772
1773 /**
1774  * g_markup_parse_context_get_element_stack:
1775  * @context: a #GMarkupParseContext
1776  *
1777  * Retrieves the element stack from the internal state of the parser.
1778  * The returned #GSList is a list of strings where the first item is
1779  * the currently open tag (as would be returned by
1780  * g_markup_parse_context_get_element()) and the next item is its
1781  * immediate parent.
1782  *
1783  * This function is intended to be used in the start_element and
1784  * end_element handlers where g_markup_parse_context_get_element()
1785  * would merely return the name of the element that is being
1786  * processed.
1787  *
1788  * Returns: the element stack, which must not be modified
1789  *
1790  * Since: 2.16
1791  **/
1792 G_CONST_RETURN GSList *
1793 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1794 {
1795   g_return_val_if_fail (context != NULL, NULL);
1796   return context->tag_stack;
1797 }
1798
1799 /**
1800  * g_markup_parse_context_get_position:
1801  * @context: a #GMarkupParseContext
1802  * @line_number: return location for a line number, or %NULL
1803  * @char_number: return location for a char-on-line number, or %NULL
1804  *
1805  * Retrieves the current line number and the number of the character on
1806  * that line. Intended for use in error messages; there are no strict
1807  * semantics for what constitutes the "current" line number other than
1808  * "the best number we could come up with for error messages."
1809  * 
1810  **/
1811 void
1812 g_markup_parse_context_get_position (GMarkupParseContext *context,
1813                                      gint                *line_number,
1814                                      gint                *char_number)
1815 {
1816   g_return_if_fail (context != NULL);
1817
1818   if (line_number)
1819     *line_number = context->line_number;
1820
1821   if (char_number)
1822     *char_number = context->char_number;
1823 }
1824
1825 /**
1826  * g_markup_parse_context_get_user_data:
1827  * @context: a #GMarkupParseContext
1828  *
1829  * Returns the user_data associated with @context.  This will either
1830  * be the user_data that was provided to g_markup_parse_context_new()
1831  * or to the most recent call of g_markup_parse_context_push().
1832  *
1833  * Returns: the provided user_data. The returned data belongs to
1834  *     the markup context and will be freed when g_markup_context_free()
1835  *     is called.
1836  *
1837  * Since: 2.18
1838  **/
1839 gpointer
1840 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1841 {
1842   return context->user_data;
1843 }
1844
1845 /**
1846  * g_markup_parse_context_push:
1847  * @context: a #GMarkupParseContext
1848  * @parser: a #GMarkupParser
1849  * @user_data: user data to pass to #GMarkupParser functions
1850  *
1851  * Temporarily redirects markup data to a sub-parser.
1852  *
1853  * This function may only be called from the start_element handler of
1854  * a #GMarkupParser.  It must be matched with a corresponding call to
1855  * g_markup_parse_context_pop() in the matching end_element handler
1856  * (except in the case that the parser aborts due to an error).
1857  *
1858  * All tags, text and other data between the matching tags is
1859  * redirected to the subparser given by @parser.  @user_data is used
1860  * as the user_data for that parser.  @user_data is also passed to the
1861  * error callback in the event that an error occurs.  This includes
1862  * errors that occur in subparsers of the subparser.
1863  *
1864  * The end tag matching the start tag for which this call was made is
1865  * handled by the previous parser (which is given its own user_data)
1866  * which is why g_markup_parse_context_pop() is provided to allow "one
1867  * last access" to the @user_data provided to this function.  In the
1868  * case of error, the @user_data provided here is passed directly to
1869  * the error callback of the subparser and g_markup_parse_context()
1870  * should not be called.  In either case, if @user_data was allocated
1871  * then it ought to be freed from both of these locations.
1872  *
1873  * This function is not intended to be directly called by users
1874  * interested in invoking subparsers.  Instead, it is intended to be
1875  * used by the subparsers themselves to implement a higher-level
1876  * interface.
1877  *
1878  * As an example, see the following implementation of a simple
1879  * parser that counts the number of tags encountered.
1880  *
1881  * |[
1882  * typedef struct
1883  * {
1884  *   gint tag_count;
1885  * } CounterData;
1886  * 
1887  * static void
1888  * counter_start_element (GMarkupParseContext  *context,
1889  *                        const gchar          *element_name,
1890  *                        const gchar         **attribute_names,
1891  *                        const gchar         **attribute_values,
1892  *                        gpointer              user_data,
1893  *                        GError              **error)
1894  * {
1895  *   CounterData *data = user_data;
1896  * 
1897  *   data->tag_count++;
1898  * }
1899  * 
1900  * static void
1901  * counter_error (GMarkupParseContext *context,
1902  *                GError              *error,
1903  *                gpointer             user_data)
1904  * {
1905  *   CounterData *data = user_data;
1906  * 
1907  *   g_slice_free (CounterData, data);
1908  * }
1909  * 
1910  * static GMarkupParser counter_subparser =
1911  * {
1912  *   counter_start_element,
1913  *   NULL,
1914  *   NULL,
1915  *   NULL,
1916  *   counter_error
1917  * };
1918  * ]|
1919  *
1920  * In order to allow this parser to be easily used as a subparser, the
1921  * following interface is provided:
1922  *
1923  * |[
1924  * void
1925  * start_counting (GMarkupParseContext *context)
1926  * {
1927  *   CounterData *data = g_slice_new (CounterData);
1928  * 
1929  *   data->tag_count = 0;
1930  *   g_markup_parse_context_push (context, &counter_subparser, data);
1931  * }
1932  * 
1933  * gint
1934  * end_counting (GMarkupParseContext *context)
1935  * {
1936  *   CounterData *data = g_markup_parse_context_pop (context);
1937  *   int result;
1938  * 
1939  *   result = data->tag_count;
1940  *   g_slice_free (CounterData, data);
1941  * 
1942  *   return result;
1943  * }
1944  * ]|
1945  *
1946  * The subparser would then be used as follows:
1947  *
1948  * |[
1949  * static void start_element (context, element_name, ...)
1950  * {
1951  *   if (strcmp (element_name, "count-these") == 0)
1952  *     start_counting (context);
1953  * 
1954  *   /&ast; else, handle other tags... &ast;/
1955  * }
1956  * 
1957  * static void end_element (context, element_name, ...)
1958  * {
1959  *   if (strcmp (element_name, "count-these") == 0)
1960  *     g_print ("Counted %d tags\n", end_counting (context));
1961  * 
1962  *   /&ast; else, handle other tags... &ast;/
1963  * }
1964  * ]|
1965  *
1966  * Since: 2.18
1967  **/
1968 void
1969 g_markup_parse_context_push (GMarkupParseContext *context,
1970                              const GMarkupParser *parser,
1971                              gpointer             user_data)
1972 {
1973   GMarkupRecursionTracker *tracker;
1974
1975   tracker = g_slice_new (GMarkupRecursionTracker);
1976   tracker->prev_element = context->subparser_element;
1977   tracker->prev_parser = context->parser;
1978   tracker->prev_user_data = context->user_data;
1979
1980   context->subparser_element = current_element (context);
1981   context->parser = parser;
1982   context->user_data = user_data;
1983
1984   context->subparser_stack = g_slist_prepend (context->subparser_stack,
1985                                               tracker);
1986 }
1987
1988 /**
1989  * g_markup_parse_context_pop:
1990  * @context: a #GMarkupParseContext
1991  *
1992  * Completes the process of a temporary sub-parser redirection.
1993  *
1994  * This function exists to collect the user_data allocated by a
1995  * matching call to g_markup_parse_context_push().  It must be called
1996  * in the end_element handler corresponding to the start_element
1997  * handler during which g_markup_parse_context_push() was called.  You
1998  * must not call this function from the error callback -- the
1999  * @user_data is provided directly to the callback in that case.
2000  *
2001  * This function is not intended to be directly called by users
2002  * interested in invoking subparsers.  Instead, it is intended to be
2003  * used by the subparsers themselves to implement a higher-level
2004  * interface.
2005  *
2006  * Returns: the user_data passed to g_markup_parse_context_push().
2007  *
2008  * Since: 2.18
2009  **/
2010 gpointer
2011 g_markup_parse_context_pop (GMarkupParseContext *context)
2012 {
2013   gpointer user_data;
2014
2015   if (!context->awaiting_pop)
2016     possibly_finish_subparser (context);
2017
2018   g_assert (context->awaiting_pop);
2019
2020   context->awaiting_pop = FALSE;
2021   
2022   /* valgrind friendliness */
2023   user_data = context->held_user_data;
2024   context->held_user_data = NULL;
2025
2026   return user_data;
2027 }
2028
2029 static void
2030 append_escaped_text (GString     *str,
2031                      const gchar *text,
2032                      gssize       length)    
2033 {
2034   const gchar *p;
2035   const gchar *end;
2036   gunichar c;
2037
2038   p = text;
2039   end = text + length;
2040
2041   while (p != end)
2042     {
2043       const gchar *next;
2044       next = g_utf8_next_char (p);
2045
2046       switch (*p)
2047         {
2048         case '&':
2049           g_string_append (str, "&amp;");
2050           break;
2051
2052         case '<':
2053           g_string_append (str, "&lt;");
2054           break;
2055
2056         case '>':
2057           g_string_append (str, "&gt;");
2058           break;
2059
2060         case '\'':
2061           g_string_append (str, "&apos;");
2062           break;
2063
2064         case '"':
2065           g_string_append (str, "&quot;");
2066           break;
2067
2068         default:
2069           c = g_utf8_get_char (p);
2070           if ((0x1 <= c && c <= 0x8) ||
2071               (0xb <= c && c  <= 0xc) ||
2072               (0xe <= c && c <= 0x1f) ||
2073               (0x7f <= c && c <= 0x84) ||
2074               (0x86 <= c && c <= 0x9f))
2075             g_string_append_printf (str, "&#x%x;", c);
2076           else
2077             g_string_append_len (str, p, next - p);
2078           break;
2079         }
2080
2081       p = next;
2082     }
2083 }
2084
2085 /**
2086  * g_markup_escape_text:
2087  * @text: some valid UTF-8 text
2088  * @length: length of @text in bytes, or -1 if the text is nul-terminated
2089  * 
2090  * Escapes text so that the markup parser will parse it verbatim.
2091  * Less than, greater than, ampersand, etc. are replaced with the
2092  * corresponding entities. This function would typically be used
2093  * when writing out a file to be parsed with the markup parser.
2094  * 
2095  * Note that this function doesn't protect whitespace and line endings
2096  * from being processed according to the XML rules for normalization
2097  * of line endings and attribute values.
2098  *
2099  * Note also that this function will produce character references in
2100  * the range of &amp;#x1; ... &amp;#x1f; for all control sequences
2101  * except for tabstop, newline and carriage return.  The character
2102  * references in this range are not valid XML 1.0, but they are
2103  * valid XML 1.1 and will be accepted by the GMarkup parser.
2104  * 
2105  * Return value: a newly allocated string with the escaped text
2106  **/
2107 gchar*
2108 g_markup_escape_text (const gchar *text,
2109                       gssize       length)  
2110 {
2111   GString *str;
2112
2113   g_return_val_if_fail (text != NULL, NULL);
2114
2115   if (length < 0)
2116     length = strlen (text);
2117
2118   /* prealloc at least as long as original text */
2119   str = g_string_sized_new (length);
2120   append_escaped_text (str, text, length);
2121
2122   return g_string_free (str, FALSE);
2123 }
2124
2125 /**
2126  * find_conversion:
2127  * @format: a printf-style format string
2128  * @after: location to store a pointer to the character after
2129  *   the returned conversion. On a %NULL return, returns the
2130  *   pointer to the trailing NUL in the string
2131  * 
2132  * Find the next conversion in a printf-style format string.
2133  * Partially based on code from printf-parser.c,
2134  * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2135  * 
2136  * Return value: pointer to the next conversion in @format,
2137  *  or %NULL, if none.
2138  **/
2139 static const char *
2140 find_conversion (const char  *format,
2141                  const char **after)
2142 {
2143   const char *start = format;
2144   const char *cp;
2145   
2146   while (*start != '\0' && *start != '%')
2147     start++;
2148
2149   if (*start == '\0')
2150     {
2151       *after = start;
2152       return NULL;
2153     }
2154
2155   cp = start + 1;
2156
2157   if (*cp == '\0')
2158     {
2159       *after = cp;
2160       return NULL;
2161     }
2162   
2163   /* Test for positional argument.  */
2164   if (*cp >= '0' && *cp <= '9')
2165     {
2166       const char *np;
2167       
2168       for (np = cp; *np >= '0' && *np <= '9'; np++)
2169         ;
2170       if (*np == '$')
2171         cp = np + 1;
2172     }
2173
2174   /* Skip the flags.  */
2175   for (;;)
2176     {
2177       if (*cp == '\'' ||
2178           *cp == '-' ||
2179           *cp == '+' ||
2180           *cp == ' ' ||
2181           *cp == '#' ||
2182           *cp == '0')
2183         cp++;
2184       else
2185         break;
2186     }
2187
2188   /* Skip the field width.  */
2189   if (*cp == '*')
2190     {
2191       cp++;
2192
2193       /* Test for positional argument.  */
2194       if (*cp >= '0' && *cp <= '9')
2195         {
2196           const char *np;
2197
2198           for (np = cp; *np >= '0' && *np <= '9'; np++)
2199             ;
2200           if (*np == '$')
2201             cp = np + 1;
2202         }
2203     }
2204   else
2205     {
2206       for (; *cp >= '0' && *cp <= '9'; cp++)
2207         ;
2208     }
2209
2210   /* Skip the precision.  */
2211   if (*cp == '.')
2212     {
2213       cp++;
2214       if (*cp == '*')
2215         {
2216           /* Test for positional argument.  */
2217           if (*cp >= '0' && *cp <= '9')
2218             {
2219               const char *np;
2220
2221               for (np = cp; *np >= '0' && *np <= '9'; np++)
2222                 ;
2223               if (*np == '$')
2224                 cp = np + 1;
2225             }
2226         }
2227       else
2228         {
2229           for (; *cp >= '0' && *cp <= '9'; cp++)
2230             ;
2231         }
2232     }
2233
2234   /* Skip argument type/size specifiers.  */
2235   while (*cp == 'h' ||
2236          *cp == 'L' ||
2237          *cp == 'l' ||
2238          *cp == 'j' ||
2239          *cp == 'z' ||
2240          *cp == 'Z' ||
2241          *cp == 't')
2242     cp++;
2243           
2244   /* Skip the conversion character.  */
2245   cp++;
2246
2247   *after = cp;
2248   return start;
2249 }
2250
2251 /**
2252  * g_markup_vprintf_escaped:
2253  * @format: printf() style format string
2254  * @args: variable argument list, similar to vprintf()
2255  * 
2256  * Formats the data in @args according to @format, escaping
2257  * all string and character arguments in the fashion
2258  * of g_markup_escape_text(). See g_markup_printf_escaped().
2259  * 
2260  * Return value: newly allocated result from formatting
2261  *  operation. Free with g_free().
2262  *
2263  * Since: 2.4
2264  **/
2265 char *
2266 g_markup_vprintf_escaped (const char *format,
2267                           va_list     args)
2268 {
2269   GString *format1;
2270   GString *format2;
2271   GString *result = NULL;
2272   gchar *output1 = NULL;
2273   gchar *output2 = NULL;
2274   const char *p, *op1, *op2;
2275   va_list args2;
2276
2277   /* The technique here, is that we make two format strings that
2278    * have the identical conversions in the identical order to the
2279    * original strings, but differ in the text in-between. We
2280    * then use the normal g_strdup_vprintf() to format the arguments
2281    * with the two new format strings. By comparing the results,
2282    * we can figure out what segments of the output come from
2283    * the the original format string, and what from the arguments,
2284    * and thus know what portions of the string to escape.
2285    *
2286    * For instance, for:
2287    *
2288    *  g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2289    *
2290    * We form the two format strings "%sX%dX" and %sY%sY". The results
2291    * of formatting with those two strings are
2292    *
2293    * "%sX%dX" => "Susan & FredX5X"
2294    * "%sY%dY" => "Susan & FredY5Y"
2295    *
2296    * To find the span of the first argument, we find the first position
2297    * where the two arguments differ, which tells us that the first
2298    * argument formatted to "Susan & Fred". We then escape that
2299    * to "Susan &amp; Fred" and join up with the intermediate portions
2300    * of the format string and the second argument to get
2301    * "Susan &amp; Fred ate 5 apples".
2302    */
2303
2304   /* Create the two modified format strings
2305    */
2306   format1 = g_string_new (NULL);
2307   format2 = g_string_new (NULL);
2308   p = format;
2309   while (TRUE)
2310     {
2311       const char *after;
2312       const char *conv = find_conversion (p, &after);
2313       if (!conv)
2314         break;
2315
2316       g_string_append_len (format1, conv, after - conv);
2317       g_string_append_c (format1, 'X');
2318       g_string_append_len (format2, conv, after - conv);
2319       g_string_append_c (format2, 'Y');
2320
2321       p = after;
2322     }
2323
2324   /* Use them to format the arguments
2325    */
2326   G_VA_COPY (args2, args);
2327   
2328   output1 = g_strdup_vprintf (format1->str, args);
2329   if (!output1)
2330     {
2331       va_end (args2);
2332       goto cleanup;
2333     }
2334   
2335   output2 = g_strdup_vprintf (format2->str, args2);
2336   va_end (args2);
2337   if (!output2)
2338     goto cleanup;
2339
2340   result = g_string_new (NULL);
2341
2342   /* Iterate through the original format string again,
2343    * copying the non-conversion portions and the escaped
2344    * converted arguments to the output string.
2345    */
2346   op1 = output1;
2347   op2 = output2;
2348   p = format;
2349   while (TRUE)
2350     {
2351       const char *after;
2352       const char *output_start;
2353       const char *conv = find_conversion (p, &after);
2354       char *escaped;
2355       
2356       if (!conv)        /* The end, after points to the trailing \0 */
2357         {
2358           g_string_append_len (result, p, after - p);
2359           break;
2360         }
2361
2362       g_string_append_len (result, p, conv - p);
2363       output_start = op1;
2364       while (*op1 == *op2)
2365         {
2366           op1++;
2367           op2++;
2368         }
2369       
2370       escaped = g_markup_escape_text (output_start, op1 - output_start);
2371       g_string_append (result, escaped);
2372       g_free (escaped);
2373       
2374       p = after;
2375       op1++;
2376       op2++;
2377     }
2378
2379  cleanup:
2380   g_string_free (format1, TRUE);
2381   g_string_free (format2, TRUE);
2382   g_free (output1);
2383   g_free (output2);
2384
2385   if (result)
2386     return g_string_free (result, FALSE);
2387   else
2388     return NULL;
2389 }
2390
2391 /**
2392  * g_markup_printf_escaped:
2393  * @format: printf() style format string
2394  * @Varargs: the arguments to insert in the format string
2395  * 
2396  * Formats arguments according to @format, escaping
2397  * all string and character arguments in the fashion
2398  * of g_markup_escape_text(). This is useful when you
2399  * want to insert literal strings into XML-style markup
2400  * output, without having to worry that the strings
2401  * might themselves contain markup.
2402  *
2403  * |[
2404  * const char *store = "Fortnum &amp; Mason";
2405  * const char *item = "Tea";
2406  * char *output;
2407  * &nbsp;
2408  * output = g_markup_printf_escaped ("&lt;purchase&gt;"
2409  *                                   "&lt;store&gt;&percnt;s&lt;/store&gt;"
2410  *                                   "&lt;item&gt;&percnt;s&lt;/item&gt;"
2411  *                                   "&lt;/purchase&gt;",
2412  *                                   store, item);
2413  * ]|
2414  * 
2415  * Return value: newly allocated result from formatting
2416  *  operation. Free with g_free().
2417  *
2418  * Since: 2.4
2419  **/
2420 char *
2421 g_markup_printf_escaped (const char *format, ...)
2422 {
2423   char *result;
2424   va_list args;
2425   
2426   va_start (args, format);
2427   result = g_markup_vprintf_escaped (format, args);
2428   va_end (args);
2429
2430   return result;
2431 }
2432
2433 static gboolean
2434 g_markup_parse_boolean (const char  *string,
2435                         gboolean    *value)
2436 {
2437   char const * const falses[] = { "false", "f", "no", "n", "0" };
2438   char const * const trues[] = { "true", "t", "yes", "y", "1" };
2439   int i;
2440
2441   for (i = 0; i < G_N_ELEMENTS (falses); i++)
2442     {
2443       if (g_ascii_strcasecmp (string, falses[i]) == 0)
2444         {
2445           if (value != NULL)
2446             *value = FALSE;
2447
2448           return TRUE;
2449         }
2450     }
2451
2452   for (i = 0; i < G_N_ELEMENTS (trues); i++)
2453     {
2454       if (g_ascii_strcasecmp (string, trues[i]) == 0)
2455         {
2456           if (value != NULL)
2457             *value = TRUE;
2458
2459           return TRUE;
2460         }
2461     }
2462
2463   return FALSE;
2464 }
2465
2466 /**
2467  * GMarkupCollectType:
2468  * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2469  *                            to collect.
2470  * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2471  *                           the attribute_values[] array.  Expects a
2472  *                           parameter of type (const char **).  If
2473  *                           %G_MARKUP_COLLECT_OPTIONAL is specified
2474  *                           and the attribute isn't present then the
2475  *                           pointer will be set to %NULL.
2476  * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2477  *                           expects a parameter of type (char **) and
2478  *                           g_strdup()s the returned pointer.  The
2479  *                           pointer must be freed with g_free().
2480  * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2481  *                            and parses the attribute value as a
2482  *                            boolean.  Sets %FALSE if the attribute
2483  *                            isn't present.  Valid boolean values
2484  *                            consist of (case insensitive) "false",
2485  *                            "f", "no", "n", "0" and "true", "t",
2486  *                            "yes", "y", "1".
2487  * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2488  *                             in the case of a missing attribute a
2489  *                             value is set that compares equal to
2490  *                             neither %FALSE nor %TRUE.
2491  *                             G_MARKUP_COLLECT_OPTIONAL is implied.
2492  * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other
2493  *                             fields.  If present, allows the
2494  *                             attribute not to appear.  A default
2495  *                             value is set depending on what value
2496  *                             type is used.
2497  *
2498  * A mixed enumerated type and flags field.  You must specify one type
2499  * (string, strdup, boolean, tristate).  Additionally, you may
2500  * optionally bitwise OR the type with the flag
2501  * %G_MARKUP_COLLECT_OPTIONAL.
2502  *
2503  * It is likely that this enum will be extended in the future to
2504  * support other types.
2505  **/
2506
2507 /**
2508  * g_markup_collect_attributes:
2509  * @element_name: the current tag name
2510  * @attribute_names: the attribute names
2511  * @attribute_values: the attribute values
2512  * @error: a pointer to a #GError or %NULL
2513  * @first_type: the #GMarkupCollectType of the
2514  *              first attribute
2515  * @first_attr: the name of the first attribute
2516  * @...: a pointer to the storage location of the
2517  *       first attribute (or %NULL), followed by
2518  *       more types names and pointers, ending
2519  *       with %G_MARKUP_COLLECT_INVALID.
2520  * 
2521  * Collects the attributes of the element from the
2522  * data passed to the #GMarkupParser start_element
2523  * function, dealing with common error conditions
2524  * and supporting boolean values.
2525  *
2526  * This utility function is not required to write
2527  * a parser but can save a lot of typing.
2528  *
2529  * The @element_name, @attribute_names,
2530  * @attribute_values and @error parameters passed
2531  * to the start_element callback should be passed
2532  * unmodified to this function.
2533  *
2534  * Following these arguments is a list of
2535  * "supported" attributes to collect.  It is an
2536  * error to specify multiple attributes with the
2537  * same name.  If any attribute not in the list
2538  * appears in the @attribute_names array then an
2539  * unknown attribute error will result.
2540  *
2541  * The #GMarkupCollectType field allows specifying
2542  * the type of collection to perform and if a
2543  * given attribute must appear or is optional.
2544  *
2545  * The attribute name is simply the name of the
2546  * attribute to collect.
2547  *
2548  * The pointer should be of the appropriate type
2549  * (see the descriptions under
2550  * #GMarkupCollectType) and may be %NULL in case a
2551  * particular attribute is to be allowed but
2552  * ignored.
2553  *
2554  * This function deals with issuing errors for missing attributes 
2555  * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes 
2556  * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate 
2557  * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well 
2558  * as parse errors for boolean-valued attributes (again of type
2559  * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE 
2560  * will be returned and @error will be set as appropriate.
2561  *
2562  * Return value: %TRUE if successful
2563  *
2564  * Since: 2.16
2565  **/
2566 gboolean
2567 g_markup_collect_attributes (const gchar         *element_name,
2568                              const gchar        **attribute_names,
2569                              const gchar        **attribute_values,
2570                              GError             **error,
2571                              GMarkupCollectType   first_type,
2572                              const gchar         *first_attr,
2573                              ...)
2574 {
2575   GMarkupCollectType type;
2576   const gchar *attr;
2577   guint64 collected;
2578   int written;
2579   va_list ap;
2580   int i;
2581
2582   type = first_type;
2583   attr = first_attr;
2584   collected = 0;
2585   written = 0;
2586
2587   va_start (ap, first_attr);
2588   while (type != G_MARKUP_COLLECT_INVALID)
2589     {
2590       gboolean mandatory;
2591       const gchar *value;
2592
2593       mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2594       type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2595
2596       /* tristate records a value != TRUE and != FALSE
2597        * for the case where the attribute is missing
2598        */
2599       if (type == G_MARKUP_COLLECT_TRISTATE)
2600         mandatory = FALSE;
2601
2602       for (i = 0; attribute_names[i]; i++)
2603         if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2604           if (!strcmp (attribute_names[i], attr))
2605             break;
2606
2607       /* ISO C99 only promises that the user can pass up to 127 arguments.
2608        * Subtracting the first 4 arguments plus the final NULL and dividing
2609        * by 3 arguments per collected attribute, we are left with a maximum
2610        * number of supported attributes of (127 - 5) / 3 = 40.
2611        *
2612        * In reality, nobody is ever going to call us with anywhere close to
2613        * 40 attributes to collect, so it is safe to assume that if i > 40
2614        * then the user has given some invalid or repeated arguments.  These
2615        * problems will be caught and reported at the end of the function.
2616        *
2617        * We know at this point that we have an error, but we don't know
2618        * what error it is, so just continue...
2619        */
2620       if (i < 40)
2621         collected |= (G_GUINT64_CONSTANT(1) << i);
2622
2623       value = attribute_values[i];
2624
2625       if (value == NULL && mandatory)
2626         {
2627           g_set_error (error, G_MARKUP_ERROR,
2628                        G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2629                        "element '%s' requires attribute '%s'",
2630                        element_name, attr);
2631
2632           va_end (ap);
2633           goto failure;
2634         }
2635
2636       switch (type)
2637         {
2638         case G_MARKUP_COLLECT_STRING:
2639           {
2640             const char **str_ptr;
2641
2642             str_ptr = va_arg (ap, const char **);
2643
2644             if (str_ptr != NULL)
2645               *str_ptr = value;
2646           }
2647           break;
2648
2649         case G_MARKUP_COLLECT_STRDUP:
2650           {
2651             char **str_ptr;
2652
2653             str_ptr = va_arg (ap, char **);
2654
2655             if (str_ptr != NULL)
2656               *str_ptr = g_strdup (value);
2657           }
2658           break;
2659
2660         case G_MARKUP_COLLECT_BOOLEAN:
2661         case G_MARKUP_COLLECT_TRISTATE:
2662           if (value == NULL)
2663             {
2664               gboolean *bool_ptr;
2665
2666               bool_ptr = va_arg (ap, gboolean *);
2667
2668               if (bool_ptr != NULL)
2669                 {
2670                   if (type == G_MARKUP_COLLECT_TRISTATE)
2671                     /* constructivists rejoice!
2672                      * neither false nor true...
2673                      */
2674                     *bool_ptr = -1;
2675
2676                   else /* G_MARKUP_COLLECT_BOOLEAN */
2677                     *bool_ptr = FALSE;
2678                 }
2679             }
2680           else
2681             {
2682               if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2683                 {
2684                   g_set_error (error, G_MARKUP_ERROR,
2685                                G_MARKUP_ERROR_INVALID_CONTENT,
2686                                "element '%s', attribute '%s', value '%s' "
2687                                "cannot be parsed as a boolean value",
2688                                element_name, attr, value);
2689
2690                   va_end (ap);
2691                   goto failure;
2692                 }
2693             }
2694
2695           break;
2696
2697         default:
2698           g_assert_not_reached ();
2699         }
2700
2701       type = va_arg (ap, GMarkupCollectType);
2702       attr = va_arg (ap, const char *);
2703       written++;
2704     }
2705   va_end (ap);
2706
2707   /* ensure we collected all the arguments */
2708   for (i = 0; attribute_names[i]; i++)
2709     if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2710       {
2711         /* attribute not collected:  could be caused by two things.
2712          *
2713          * 1) it doesn't exist in our list of attributes
2714          * 2) it existed but was matched by a duplicate attribute earlier
2715          *
2716          * find out.
2717          */
2718         int j;
2719
2720         for (j = 0; j < i; j++)
2721           if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2722             /* duplicate! */
2723             break;
2724
2725         /* j is now the first occurrence of attribute_names[i] */
2726         if (i == j)
2727           g_set_error (error, G_MARKUP_ERROR,
2728                        G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2729                        "attribute '%s' invalid for element '%s'",
2730                        attribute_names[i], element_name);
2731         else
2732           g_set_error (error, G_MARKUP_ERROR,
2733                        G_MARKUP_ERROR_INVALID_CONTENT,
2734                        "attribute '%s' given multiple times for element '%s'",
2735                        attribute_names[i], element_name);
2736
2737         goto failure;
2738       }
2739
2740   return TRUE;
2741
2742 failure:
2743   /* replay the above to free allocations */
2744   type = first_type;
2745   attr = first_attr;
2746
2747   va_start (ap, first_attr);
2748   while (type != G_MARKUP_COLLECT_INVALID)
2749     {
2750       gpointer ptr;
2751
2752       ptr = va_arg (ap, gpointer);
2753
2754       if (ptr == NULL)
2755         continue;
2756
2757       switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2758         {
2759         case G_MARKUP_COLLECT_STRDUP:
2760           if (written)
2761             g_free (*(char **) ptr);
2762
2763         case G_MARKUP_COLLECT_STRING:
2764           *(char **) ptr = NULL;
2765           break;
2766
2767         case G_MARKUP_COLLECT_BOOLEAN:
2768           *(gboolean *) ptr = FALSE;
2769           break;
2770
2771         case G_MARKUP_COLLECT_TRISTATE:
2772           *(gboolean *) ptr = -1;
2773           break;
2774         }
2775
2776       type = va_arg (ap, GMarkupCollectType);
2777       attr = va_arg (ap, const char *);
2778
2779       if (written)
2780         written--;
2781     }
2782   va_end (ap);
2783
2784   return FALSE;
2785 }