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