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