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