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