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