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