Clarify docs.
[platform/upstream/glib.git] / glib / gmarkup.c
1 /* gmarkup.c - Simple XML-like parser
2  *
3  *  Copyright 2000, 2003 Red Hat, Inc.
4  *
5  * GLib is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU Lesser General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * GLib is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with GLib; see the file COPYING.LIB.  If not,
17  * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  *   Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include <stdarg.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28
29 #include "glib.h"
30 #include "galias.h"
31
32 #include "glibintl.h"
33
34 GQuark
35 g_markup_error_quark (void)
36 {
37   static GQuark error_quark = 0;
38
39   if (error_quark == 0)
40     error_quark = g_quark_from_static_string ("g-markup-error-quark");
41
42   return error_quark;
43 }
44
45 typedef enum
46 {
47   STATE_START,
48   STATE_AFTER_OPEN_ANGLE,
49   STATE_AFTER_CLOSE_ANGLE,
50   STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
51   STATE_INSIDE_OPEN_TAG_NAME,
52   STATE_INSIDE_ATTRIBUTE_NAME,
53   STATE_AFTER_ATTRIBUTE_NAME,
54   STATE_BETWEEN_ATTRIBUTES,
55   STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
56   STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
57   STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
58   STATE_INSIDE_TEXT,
59   STATE_AFTER_CLOSE_TAG_SLASH,
60   STATE_INSIDE_CLOSE_TAG_NAME,
61   STATE_AFTER_CLOSE_TAG_NAME,
62   STATE_INSIDE_PASSTHROUGH,
63   STATE_ERROR
64 } GMarkupParseState;
65
66 struct _GMarkupParseContext
67 {
68   const GMarkupParser *parser;
69
70   GMarkupParseFlags flags;
71
72   gint line_number;
73   gint char_number;
74
75   gpointer user_data;
76   GDestroyNotify dnotify;
77
78   /* A piece of character data or an element that
79    * hasn't "ended" yet so we haven't yet called
80    * the callback for it.
81    */
82   GString *partial_chunk;
83
84   GMarkupParseState state;
85   GSList *tag_stack;
86   gchar **attr_names;
87   gchar **attr_values;
88   gint cur_attr;
89   gint alloc_attrs;
90
91   const gchar *current_text;
92   gssize       current_text_len;      
93   const gchar *current_text_end;
94
95   GString *leftover_char_portion;
96
97   /* used to save the start of the last interesting thingy */
98   const gchar *start;
99
100   const gchar *iter;
101
102   guint document_empty : 1;
103   guint parsing : 1;
104   gint balance;
105 };
106
107 /**
108  * g_markup_parse_context_new:
109  * @parser: a #GMarkupParser
110  * @flags: one or more #GMarkupParseFlags
111  * @user_data: user data to pass to #GMarkupParser functions
112  * @user_data_dnotify: user data destroy notifier called when the parse context is freed
113  * 
114  * Creates a new parse context. A parse context is used to parse
115  * marked-up documents. You can feed any number of documents into
116  * a context, as long as no errors occur; once an error occurs,
117  * the parse context can't continue to parse text (you have to free it
118  * and create a new parse context).
119  * 
120  * Return value: a new #GMarkupParseContext
121  **/
122 GMarkupParseContext *
123 g_markup_parse_context_new (const GMarkupParser *parser,
124                             GMarkupParseFlags    flags,
125                             gpointer             user_data,
126                             GDestroyNotify       user_data_dnotify)
127 {
128   GMarkupParseContext *context;
129
130   g_return_val_if_fail (parser != NULL, NULL);
131
132   context = g_new (GMarkupParseContext, 1);
133
134   context->parser = parser;
135   context->flags = flags;
136   context->user_data = user_data;
137   context->dnotify = user_data_dnotify;
138
139   context->line_number = 1;
140   context->char_number = 1;
141
142   context->partial_chunk = NULL;
143
144   context->state = STATE_START;
145   context->tag_stack = NULL;
146   context->attr_names = NULL;
147   context->attr_values = NULL;
148   context->cur_attr = -1;
149   context->alloc_attrs = 0;
150
151   context->current_text = NULL;
152   context->current_text_len = -1;
153   context->current_text_end = NULL;
154   context->leftover_char_portion = NULL;
155
156   context->start = NULL;
157   context->iter = NULL;
158
159   context->document_empty = TRUE;
160   context->parsing = FALSE;
161
162   context->balance = 0;
163
164   return context;
165 }
166
167 /**
168  * g_markup_parse_context_free:
169  * @context: a #GMarkupParseContext
170  * 
171  * Frees a #GMarkupParseContext. Can't be called from inside
172  * one of the #GMarkupParser functions.
173  * 
174  **/
175 void
176 g_markup_parse_context_free (GMarkupParseContext *context)
177 {
178   g_return_if_fail (context != NULL);
179   g_return_if_fail (!context->parsing);
180
181   if (context->dnotify)
182     (* context->dnotify) (context->user_data);
183
184   g_strfreev (context->attr_names);
185   g_strfreev (context->attr_values);
186
187   g_slist_foreach (context->tag_stack, (GFunc)g_free, NULL);
188   g_slist_free (context->tag_stack);
189
190   if (context->partial_chunk)
191     g_string_free (context->partial_chunk, TRUE);
192
193   if (context->leftover_char_portion)
194     g_string_free (context->leftover_char_portion, TRUE);
195
196   g_free (context);
197 }
198
199 static void
200 mark_error (GMarkupParseContext *context,
201             GError              *error)
202 {
203   context->state = STATE_ERROR;
204
205   if (context->parser->error)
206     (*context->parser->error) (context, error, context->user_data);
207 }
208
209 static void set_error (GMarkupParseContext *context,
210                        GError             **error,
211                        GMarkupError         code,
212                        const gchar         *format,
213                        ...) G_GNUC_PRINTF (4, 5);
214
215 static void
216 set_error (GMarkupParseContext *context,
217            GError             **error,
218            GMarkupError         code,
219            const gchar         *format,
220            ...)
221 {
222   GError *tmp_error;
223   gchar *s;
224   va_list args;
225
226   va_start (args, format);
227   s = g_strdup_vprintf (format, args);
228   va_end (args);
229
230   tmp_error = g_error_new (G_MARKUP_ERROR,
231                            code,
232                            _("Error on line %d char %d: %s"),
233                            context->line_number,
234                            context->char_number,
235                            s);
236
237   g_free (s);
238
239   mark_error (context, tmp_error);
240
241   g_propagate_error (error, tmp_error);
242 }
243
244
245 /* To make these faster, we first use the ascii-only tests, then check
246  * for the usual non-alnum name-end chars, and only then call the
247  * expensive unicode stuff. Nobody uses non-ascii in XML tag/attribute
248  * names, so this is a reasonable hack that virtually always avoids
249  * the guniprop call.
250  */
251 #define IS_COMMON_NAME_END_CHAR(c) \
252   ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
253
254 static gboolean
255 is_name_start_char (const gchar *p)
256 {
257   if (g_ascii_isalpha (*p) ||
258       (!IS_COMMON_NAME_END_CHAR (*p) &&
259        (*p == '_' || 
260         *p == ':' ||
261         g_unichar_isalpha (g_utf8_get_char (p)))))
262     return TRUE;
263   else
264     return FALSE;
265 }
266
267 static gboolean
268 is_name_char (const gchar *p)
269 {
270   if (g_ascii_isalnum (*p) ||
271       (!IS_COMMON_NAME_END_CHAR (*p) &&
272        (*p == '.' || 
273         *p == '-' ||
274         *p == '_' ||
275         *p == ':' ||
276         g_unichar_isalpha (g_utf8_get_char (p)))))
277     return TRUE;
278   else
279     return FALSE;
280 }
281
282
283 static gchar*
284 char_str (gunichar c,
285           gchar   *buf)
286 {
287   memset (buf, 0, 8);
288   g_unichar_to_utf8 (c, buf);
289   return buf;
290 }
291
292 static gchar*
293 utf8_str (const gchar *utf8,
294           gchar       *buf)
295 {
296   char_str (g_utf8_get_char (utf8), buf);
297   return buf;
298 }
299
300 static void
301 set_unescape_error (GMarkupParseContext *context,
302                     GError             **error,
303                     const gchar         *remaining_text,
304                     const gchar         *remaining_text_end,
305                     GMarkupError         code,
306                     const gchar         *format,
307                     ...)
308 {
309   GError *tmp_error;
310   gchar *s;
311   va_list args;
312   gint remaining_newlines;
313   const gchar *p;
314
315   remaining_newlines = 0;
316   p = remaining_text;
317   while (p != remaining_text_end)
318     {
319       if (*p == '\n')
320         ++remaining_newlines;
321       ++p;
322     }
323
324   va_start (args, format);
325   s = g_strdup_vprintf (format, args);
326   va_end (args);
327
328   tmp_error = g_error_new (G_MARKUP_ERROR,
329                            code,
330                            _("Error on line %d: %s"),
331                            context->line_number - remaining_newlines,
332                            s);
333
334   g_free (s);
335
336   mark_error (context, tmp_error);
337
338   g_propagate_error (error, tmp_error);
339 }
340
341 typedef enum
342 {
343   USTATE_INSIDE_TEXT,
344   USTATE_AFTER_AMPERSAND,
345   USTATE_INSIDE_ENTITY_NAME,
346   USTATE_AFTER_CHARREF_HASH
347 } UnescapeState;
348
349 typedef struct
350 {
351   GMarkupParseContext *context;
352   GString *str;
353   UnescapeState state;
354   const gchar *text;
355   const gchar *text_end;
356   const gchar *entity_start;
357 } UnescapeContext;
358
359 static const gchar*
360 unescape_text_state_inside_text (UnescapeContext *ucontext,
361                                  const gchar     *p,
362                                  GError         **error)
363 {
364   const gchar *start;
365   gboolean normalize_attribute;
366
367   if (ucontext->context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
368       ucontext->context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
369     normalize_attribute = TRUE;
370   else
371     normalize_attribute = FALSE;
372
373   start = p;
374   
375   while (p != ucontext->text_end)
376     {
377       if (*p == '&')
378         {
379           break;
380         }
381       else if (normalize_attribute && (*p == '\t' || *p == '\n'))
382         {
383           g_string_append_len (ucontext->str, start, p - start);
384           g_string_append_c (ucontext->str, ' ');
385           p = g_utf8_next_char (p);
386           start = p;
387         }
388       else if (*p == '\r')
389         {
390           g_string_append_len (ucontext->str, start, p - start);
391           g_string_append_c (ucontext->str, normalize_attribute ? ' ' : '\n');
392           p = g_utf8_next_char (p);
393           if (p != ucontext->text_end && *p == '\n')
394             p = g_utf8_next_char (p);
395           start = p;
396         }
397       else
398         p = g_utf8_next_char (p);
399     }
400   
401   if (p != start)
402     g_string_append_len (ucontext->str, start, p - start);
403   
404   if (p != ucontext->text_end && *p == '&')
405     {
406       p = g_utf8_next_char (p);
407       ucontext->state = USTATE_AFTER_AMPERSAND;
408     }
409
410   return p;
411 }
412
413 static const gchar*
414 unescape_text_state_after_ampersand (UnescapeContext *ucontext,
415                                      const gchar     *p,
416                                      GError         **error)
417 {
418   ucontext->entity_start = NULL;
419   
420   if (*p == '#')
421     {
422       p = g_utf8_next_char (p);
423
424       ucontext->entity_start = p;
425       ucontext->state = USTATE_AFTER_CHARREF_HASH;
426     }
427   else if (!is_name_start_char (p))
428     {
429       if (*p == ';')
430         {
431           set_unescape_error (ucontext->context, error,
432                               p, ucontext->text_end,
433                               G_MARKUP_ERROR_PARSE,
434                               _("Empty entity '&;' seen; valid "
435                                 "entities are: &amp; &quot; &lt; &gt; &apos;"));
436         }
437       else
438         {
439           gchar buf[8];
440
441           set_unescape_error (ucontext->context, error,
442                               p, ucontext->text_end,
443                               G_MARKUP_ERROR_PARSE,
444                               _("Character '%s' is not valid at "
445                                 "the start of an entity name; "
446                                 "the & character begins an entity; "
447                                 "if this ampersand isn't supposed "
448                                 "to be an entity, escape it as "
449                                 "&amp;"),
450                               utf8_str (p, buf));
451         }
452     }
453   else
454     {
455       ucontext->entity_start = p;
456       ucontext->state = USTATE_INSIDE_ENTITY_NAME;
457     }
458
459   return p;
460 }
461
462 static const gchar*
463 unescape_text_state_inside_entity_name (UnescapeContext *ucontext,
464                                         const gchar     *p,
465                                         GError         **error)
466 {
467   while (p != ucontext->text_end)
468     {
469       if (*p == ';')
470         break;
471       else if (!is_name_char (p))
472         {
473           gchar ubuf[8];
474
475           set_unescape_error (ucontext->context, error,
476                               p, ucontext->text_end,
477                               G_MARKUP_ERROR_PARSE,
478                               _("Character '%s' is not valid "
479                                 "inside an entity name"),
480                               utf8_str (p, ubuf));
481           break;
482         }
483
484       p = g_utf8_next_char (p);
485     }
486
487   if (ucontext->context->state != STATE_ERROR)
488     {
489       if (p != ucontext->text_end)
490         {
491           gint len = p - ucontext->entity_start;
492
493           /* move to after semicolon */
494           p = g_utf8_next_char (p);
495           ucontext->state = USTATE_INSIDE_TEXT;
496
497           if (strncmp (ucontext->entity_start, "lt", len) == 0)
498             g_string_append_c (ucontext->str, '<');
499           else if (strncmp (ucontext->entity_start, "gt", len) == 0)
500             g_string_append_c (ucontext->str, '>');
501           else if (strncmp (ucontext->entity_start, "amp", len) == 0)
502             g_string_append_c (ucontext->str, '&');
503           else if (strncmp (ucontext->entity_start, "quot", len) == 0)
504             g_string_append_c (ucontext->str, '"');
505           else if (strncmp (ucontext->entity_start, "apos", len) == 0)
506             g_string_append_c (ucontext->str, '\'');
507           else
508             {
509               gchar *name;
510
511               name = g_strndup (ucontext->entity_start, len);
512               set_unescape_error (ucontext->context, error,
513                                   p, ucontext->text_end,
514                                   G_MARKUP_ERROR_PARSE,
515                                   _("Entity name '%s' is not known"),
516                                   name);
517               g_free (name);
518             }
519         }
520       else
521         {
522           set_unescape_error (ucontext->context, error,
523                               /* give line number of the & */
524                               ucontext->entity_start, ucontext->text_end,
525                               G_MARKUP_ERROR_PARSE,
526                               _("Entity did not end with a semicolon; "
527                                 "most likely you used an ampersand "
528                                 "character without intending to start "
529                                 "an entity - escape ampersand as &amp;"));
530         }
531     }
532 #undef MAX_ENT_LEN
533
534   return p;
535 }
536
537 static const gchar*
538 unescape_text_state_after_charref_hash (UnescapeContext *ucontext,
539                                         const gchar     *p,
540                                         GError         **error)
541 {
542   gboolean is_hex = FALSE;
543   const char *start;
544
545   start = ucontext->entity_start;
546
547   if (*p == 'x')
548     {
549       is_hex = TRUE;
550       p = g_utf8_next_char (p);
551       start = p;
552     }
553
554   while (p != ucontext->text_end && *p != ';')
555     p = g_utf8_next_char (p);
556
557   if (p != ucontext->text_end)
558     {
559       g_assert (*p == ';');
560
561       /* digit is between start and p */
562
563       if (start != p)
564         {
565           gulong l;
566           gchar *end = NULL;
567                     
568           errno = 0;
569           if (is_hex)
570             l = strtoul (start, &end, 16);
571           else
572             l = strtoul (start, &end, 10);
573
574           if (end != p || errno != 0)
575             {
576               set_unescape_error (ucontext->context, error,
577                                   start, ucontext->text_end,
578                                   G_MARKUP_ERROR_PARSE,
579                                   _("Failed to parse '%-.*s', which "
580                                     "should have been a digit "
581                                     "inside a character reference "
582                                     "(&#234; for example) - perhaps "
583                                     "the digit is too large"),
584                                   p - start, start);
585             }
586           else
587             {
588               /* characters XML permits */
589               if (l == 0x9 ||
590                   l == 0xA ||
591                   l == 0xD ||
592                   (l >= 0x20 && l <= 0xD7FF) ||
593                   (l >= 0xE000 && l <= 0xFFFD) ||
594                   (l >= 0x10000 && l <= 0x10FFFF))
595                 {
596                   gchar buf[8];
597                   g_string_append (ucontext->str, char_str (l, buf));
598                 }
599               else
600                 {
601                   set_unescape_error (ucontext->context, error,
602                                       start, ucontext->text_end,
603                                       G_MARKUP_ERROR_PARSE,
604                                       _("Character reference '%-.*s' does not "
605                                         "encode a permitted character"),
606                                       p - start, start);
607                 }
608             }
609
610           /* Move to next state */
611           p = g_utf8_next_char (p); /* past semicolon */
612           ucontext->state = USTATE_INSIDE_TEXT;
613         }
614       else
615         {
616           set_unescape_error (ucontext->context, error,
617                               start, ucontext->text_end,
618                               G_MARKUP_ERROR_PARSE,
619                               _("Empty character reference; "
620                                 "should include a digit such as "
621                                 "&#454;"));
622         }
623     }
624   else
625     {
626       set_unescape_error (ucontext->context, error,
627                           start, ucontext->text_end,
628                           G_MARKUP_ERROR_PARSE,
629                           _("Character reference did not end with a "
630                             "semicolon; "
631                             "most likely you used an ampersand "
632                             "character without intending to start "
633                             "an entity - escape ampersand as &amp;"));
634     }
635
636   return p;
637 }
638
639 static gboolean
640 unescape_text (GMarkupParseContext *context,
641                const gchar         *text,
642                const gchar         *text_end,
643                GString            **unescaped,
644                GError             **error)
645 {
646   UnescapeContext ucontext;
647   const gchar *p;
648
649   ucontext.context = context;
650   ucontext.text = text;
651   ucontext.text_end = text_end;
652   ucontext.entity_start = NULL;
653   
654   ucontext.str = g_string_sized_new (text_end - text);
655
656   ucontext.state = USTATE_INSIDE_TEXT;
657   p = text;
658
659   while (p != text_end && context->state != STATE_ERROR)
660     {
661       g_assert (p < text_end);
662       
663       switch (ucontext.state)
664         {
665         case USTATE_INSIDE_TEXT:
666           {
667             p = unescape_text_state_inside_text (&ucontext,
668                                                  p,
669                                                  error);
670           }
671           break;
672
673         case USTATE_AFTER_AMPERSAND:
674           {
675             p = unescape_text_state_after_ampersand (&ucontext,
676                                                      p,
677                                                      error);
678           }
679           break;
680
681
682         case USTATE_INSIDE_ENTITY_NAME:
683           {
684             p = unescape_text_state_inside_entity_name (&ucontext,
685                                                         p,
686                                                         error);
687           }
688           break;
689
690         case USTATE_AFTER_CHARREF_HASH:
691           {
692             p = unescape_text_state_after_charref_hash (&ucontext,
693                                                         p,
694                                                         error);
695           }
696           break;
697
698         default:
699           g_assert_not_reached ();
700           break;
701         }
702     }
703
704   if (context->state != STATE_ERROR) 
705     {
706       switch (ucontext.state) 
707         {
708         case USTATE_INSIDE_TEXT:
709           break;
710         case USTATE_AFTER_AMPERSAND:
711         case USTATE_INSIDE_ENTITY_NAME:
712           set_unescape_error (context, error,
713                               NULL, NULL,
714                               G_MARKUP_ERROR_PARSE,
715                               _("Unfinished entity reference"));
716           break;
717         case USTATE_AFTER_CHARREF_HASH:
718           set_unescape_error (context, error,
719                               NULL, NULL,
720                               G_MARKUP_ERROR_PARSE,
721                               _("Unfinished character reference"));
722           break;
723         }
724     }
725
726   if (context->state == STATE_ERROR)
727     {
728       g_string_free (ucontext.str, TRUE);
729       *unescaped = NULL;
730       return FALSE;
731     }
732   else
733     {
734       *unescaped = ucontext.str;
735       return TRUE;
736     }
737 }
738
739 static inline gboolean
740 advance_char (GMarkupParseContext *context)
741 {  
742   context->iter = g_utf8_next_char (context->iter);
743   context->char_number += 1;
744
745   if (context->iter == context->current_text_end)
746     {
747       return FALSE;
748     }
749   else if (*context->iter == '\n')
750     {
751       context->line_number += 1;
752       context->char_number = 1;
753     }
754   
755   return TRUE;
756 }
757
758 static inline gboolean
759 xml_isspace (char c)
760 {
761   return c == ' ' || c == '\t' || c == '\n' || c == '\r';
762 }
763
764 static void
765 skip_spaces (GMarkupParseContext *context)
766 {
767   do
768     {
769       if (!xml_isspace (*context->iter))
770         return;
771     }
772   while (advance_char (context));
773 }
774
775 static void
776 advance_to_name_end (GMarkupParseContext *context)
777 {
778   do
779     {
780       if (!is_name_char (context->iter))
781         return;
782     }
783   while (advance_char (context));
784 }
785
786 static void
787 add_to_partial (GMarkupParseContext *context,
788                 const gchar         *text_start,
789                 const gchar         *text_end)
790 {
791   if (context->partial_chunk == NULL)
792     context->partial_chunk = g_string_sized_new (text_end - text_start);
793
794   if (text_start != text_end)
795     g_string_append_len (context->partial_chunk, text_start,
796                          text_end - text_start);
797
798   /* Invariant here that partial_chunk exists */
799 }
800
801 static void
802 truncate_partial (GMarkupParseContext *context)
803 {
804   if (context->partial_chunk != NULL)
805     {
806       context->partial_chunk = g_string_truncate (context->partial_chunk, 0);
807     }
808 }
809
810 static const gchar*
811 current_element (GMarkupParseContext *context)
812 {
813   return context->tag_stack->data;
814 }
815
816 static const gchar*
817 current_attribute (GMarkupParseContext *context)
818 {
819   g_assert (context->cur_attr >= 0);
820   return context->attr_names[context->cur_attr];
821 }
822
823 static void
824 find_current_text_end (GMarkupParseContext *context)
825 {
826   /* This function must be safe (non-segfaulting) on invalid UTF8.
827    * It assumes the string starts with a character start
828    */
829   const gchar *end = context->current_text + context->current_text_len;
830   const gchar *p;
831   const gchar *next;
832
833   g_assert (context->current_text_len > 0);
834
835   p = g_utf8_find_prev_char (context->current_text, end);
836
837   g_assert (p != NULL); /* since current_text was a char start */
838
839   /* p is now the start of the last character or character portion. */
840   g_assert (p != end);
841   next = g_utf8_next_char (p); /* this only touches *p, nothing beyond */
842
843   if (next == end)
844     {
845       /* whole character */
846       context->current_text_end = end;
847     }
848   else
849     {
850       /* portion */
851       context->leftover_char_portion = g_string_new_len (p, end - p);
852       context->current_text_len -= (end - p);
853       context->current_text_end = p;
854     }
855 }
856
857
858 static void
859 add_attribute (GMarkupParseContext *context, char *name)
860 {
861   if (context->cur_attr + 2 >= context->alloc_attrs)
862     {
863       context->alloc_attrs += 5; /* silly magic number */
864       context->attr_names = g_realloc (context->attr_names, sizeof(char*)*context->alloc_attrs);
865       context->attr_values = g_realloc (context->attr_values, sizeof(char*)*context->alloc_attrs);
866     }
867   context->cur_attr++;
868   context->attr_names[context->cur_attr] = name;
869   context->attr_values[context->cur_attr] = NULL;
870   context->attr_names[context->cur_attr+1] = NULL;
871   context->attr_values[context->cur_attr+1] = NULL;
872 }
873
874 /**
875  * g_markup_parse_context_parse:
876  * @context: a #GMarkupParseContext
877  * @text: chunk of text to parse
878  * @text_len: length of @text in bytes
879  * @error: return location for a #GError
880  * 
881  * Feed some data to the #GMarkupParseContext. The data need not
882  * be valid UTF-8; an error will be signaled if it's invalid.
883  * The data need not be an entire document; you can feed a document
884  * into the parser incrementally, via multiple calls to this function.
885  * Typically, as you receive data from a network connection or file,
886  * you feed each received chunk of data into this function, aborting
887  * the process if an error occurs. Once an error is reported, no further
888  * data may be fed to the #GMarkupParseContext; all errors are fatal.
889  * 
890  * Return value: %FALSE if an error occurred, %TRUE on success
891  **/
892 gboolean
893 g_markup_parse_context_parse (GMarkupParseContext *context,
894                               const gchar         *text,
895                               gssize               text_len,
896                               GError             **error)
897 {
898   const gchar *first_invalid;
899   
900   g_return_val_if_fail (context != NULL, FALSE);
901   g_return_val_if_fail (text != NULL, FALSE);
902   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
903   g_return_val_if_fail (!context->parsing, FALSE);
904   
905   if (text_len < 0)
906     text_len = strlen (text);
907
908   if (text_len == 0)
909     return TRUE;
910   
911   context->parsing = TRUE;
912   
913   if (context->leftover_char_portion)
914     {
915       const gchar *first_char;
916
917       if ((*text & 0xc0) != 0x80)
918         first_char = text;
919       else
920         first_char = g_utf8_find_next_char (text, text + text_len);
921
922       if (first_char)
923         {
924           /* leftover_char_portion was completed. Parse it. */
925           GString *portion = context->leftover_char_portion;
926           
927           g_string_append_len (context->leftover_char_portion,
928                                text, first_char - text);
929
930           /* hacks to allow recursion */
931           context->parsing = FALSE;
932           context->leftover_char_portion = NULL;
933           
934           if (!g_markup_parse_context_parse (context,
935                                              portion->str, portion->len,
936                                              error))
937             {
938               g_assert (context->state == STATE_ERROR);
939             }
940           
941           g_string_free (portion, TRUE);
942           context->parsing = TRUE;
943
944           /* Skip the fraction of char that was in this text */
945           text_len -= (first_char - text);
946           text = first_char;
947         }
948       else
949         {
950           /* another little chunk of the leftover char; geez
951            * someone is inefficient.
952            */
953           g_string_append_len (context->leftover_char_portion,
954                                text, text_len);
955
956           if (context->leftover_char_portion->len > 7)
957             {
958               /* The leftover char portion is too big to be
959                * a UTF-8 character
960                */
961               set_error (context,
962                          error,
963                          G_MARKUP_ERROR_BAD_UTF8,
964                          _("Invalid UTF-8 encoded text"));
965             }
966           
967           goto finished;
968         }
969     }
970
971   context->current_text = text;
972   context->current_text_len = text_len;
973   context->iter = context->current_text;
974   context->start = context->iter;
975
976   /* Nothing left after finishing the leftover char, or nothing
977    * passed in to begin with.
978    */
979   if (context->current_text_len == 0)
980     goto finished;
981
982   /* find_current_text_end () assumes the string starts at
983    * a character start, so we need to validate at least
984    * that much. It doesn't assume any following bytes
985    * are valid.
986    */
987   if ((*context->current_text & 0xc0) == 0x80) /* not a char start */
988     {
989       set_error (context,
990                  error,
991                  G_MARKUP_ERROR_BAD_UTF8,
992                  _("Invalid UTF-8 encoded text"));
993       goto finished;
994     }
995
996   /* Initialize context->current_text_end, possibly adjusting
997    * current_text_len, and add any leftover char portion
998    */
999   find_current_text_end (context);
1000
1001   /* Validate UTF8 (must be done after we find the end, since
1002    * we could have a trailing incomplete char)
1003    */
1004   if (!g_utf8_validate (context->current_text,
1005                         context->current_text_len,
1006                         &first_invalid))
1007     {
1008       gint newlines = 0;
1009       const gchar *p;
1010       p = context->current_text;
1011       while (p != context->current_text_end)
1012         {
1013           if (*p == '\n')
1014             ++newlines;
1015           ++p;
1016         }
1017
1018       context->line_number += newlines;
1019
1020       set_error (context,
1021                  error,
1022                  G_MARKUP_ERROR_BAD_UTF8,
1023                  _("Invalid UTF-8 encoded text"));
1024       goto finished;
1025     }
1026
1027   while (context->iter != context->current_text_end)
1028     {
1029       switch (context->state)
1030         {
1031         case STATE_START:
1032           /* Possible next state: AFTER_OPEN_ANGLE */
1033
1034           g_assert (context->tag_stack == NULL);
1035
1036           /* whitespace is ignored outside of any elements */
1037           skip_spaces (context);
1038
1039           if (context->iter != context->current_text_end)
1040             {
1041               if (*context->iter == '<')
1042                 {
1043                   /* Move after the open angle */
1044                   advance_char (context);
1045
1046                   context->state = STATE_AFTER_OPEN_ANGLE;
1047
1048                   /* this could start a passthrough */
1049                   context->start = context->iter;
1050
1051                   /* document is now non-empty */
1052                   context->document_empty = FALSE;
1053                 }
1054               else
1055                 {
1056                   set_error (context,
1057                              error,
1058                              G_MARKUP_ERROR_PARSE,
1059                              _("Document must begin with an element (e.g. <book>)"));
1060                 }
1061             }
1062           break;
1063
1064         case STATE_AFTER_OPEN_ANGLE:
1065           /* Possible next states: INSIDE_OPEN_TAG_NAME,
1066            *  AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1067            */
1068           if (*context->iter == '?' ||
1069               *context->iter == '!')
1070             {
1071               /* include < in the passthrough */
1072               const gchar *openangle = "<";
1073               add_to_partial (context, openangle, openangle + 1);
1074               context->start = context->iter;
1075               context->balance = 1;
1076               context->state = STATE_INSIDE_PASSTHROUGH;
1077             }
1078           else if (*context->iter == '/')
1079             {
1080               /* move after it */
1081               advance_char (context);
1082
1083               context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1084             }
1085           else if (is_name_start_char (context->iter))
1086             {
1087               context->state = STATE_INSIDE_OPEN_TAG_NAME;
1088
1089               /* start of tag name */
1090               context->start = context->iter;
1091             }
1092           else
1093             {
1094               gchar buf[8];
1095
1096               set_error (context,
1097                          error,
1098                          G_MARKUP_ERROR_PARSE,
1099                          _("'%s' is not a valid character following "
1100                            "a '<' character; it may not begin an "
1101                            "element name"),
1102                          utf8_str (context->iter, buf));
1103             }
1104           break;
1105
1106           /* The AFTER_CLOSE_ANGLE state is actually sort of
1107            * broken, because it doesn't correspond to a range
1108            * of characters in the input stream as the others do,
1109            * and thus makes things harder to conceptualize
1110            */
1111         case STATE_AFTER_CLOSE_ANGLE:
1112           /* Possible next states: INSIDE_TEXT, STATE_START */
1113           if (context->tag_stack == NULL)
1114             {
1115               context->start = NULL;
1116               context->state = STATE_START;
1117             }
1118           else
1119             {
1120               context->start = context->iter;
1121               context->state = STATE_INSIDE_TEXT;
1122             }
1123           break;
1124
1125         case STATE_AFTER_ELISION_SLASH:
1126           /* Possible next state: AFTER_CLOSE_ANGLE */
1127
1128           {
1129             /* We need to pop the tag stack and call the end_element
1130              * function, since this is the close tag
1131              */
1132             GError *tmp_error = NULL;
1133           
1134             g_assert (context->tag_stack != NULL);
1135
1136             tmp_error = NULL;
1137             if (context->parser->end_element)
1138               (* context->parser->end_element) (context,
1139                                                 context->tag_stack->data,
1140                                                 context->user_data,
1141                                                 &tmp_error);
1142           
1143             if (tmp_error)
1144               {
1145                 mark_error (context, tmp_error);
1146                 g_propagate_error (error, tmp_error);
1147               }          
1148             else
1149               {
1150                 if (*context->iter == '>')
1151                   {
1152                     /* move after the close angle */
1153                     advance_char (context);
1154                     context->state = STATE_AFTER_CLOSE_ANGLE;
1155                   }
1156                 else
1157                   {
1158                     gchar buf[8];
1159
1160                     set_error (context,
1161                                error,
1162                                G_MARKUP_ERROR_PARSE,
1163                                _("Odd character '%s', expected a '>' character "
1164                                  "to end the start tag of element '%s'"),
1165                                utf8_str (context->iter, buf),
1166                                current_element (context));
1167                   }
1168               }
1169
1170             g_free (context->tag_stack->data);
1171             context->tag_stack = g_slist_delete_link (context->tag_stack,
1172                                                       context->tag_stack);
1173           }
1174           break;
1175
1176         case STATE_INSIDE_OPEN_TAG_NAME:
1177           /* Possible next states: BETWEEN_ATTRIBUTES */
1178
1179           /* if there's a partial chunk then it's the first part of the
1180            * tag name. If there's a context->start then it's the start
1181            * of the tag name in current_text, the partial chunk goes
1182            * before that start though.
1183            */
1184           advance_to_name_end (context);
1185
1186           if (context->iter == context->current_text_end)
1187             {
1188               /* The name hasn't necessarily ended. Merge with
1189                * partial chunk, leave state unchanged.
1190                */
1191               add_to_partial (context, context->start, context->iter);
1192             }
1193           else
1194             {
1195               /* The name has ended. Combine it with the partial chunk
1196                * if any; push it on the stack; enter next state.
1197                */
1198               add_to_partial (context, context->start, context->iter);
1199               context->tag_stack =
1200                 g_slist_prepend (context->tag_stack,
1201                                  g_string_free (context->partial_chunk,
1202                                                 FALSE));
1203
1204               context->partial_chunk = NULL;
1205
1206               context->state = STATE_BETWEEN_ATTRIBUTES;
1207               context->start = NULL;
1208             }
1209           break;
1210
1211         case STATE_INSIDE_ATTRIBUTE_NAME:
1212           /* Possible next states: AFTER_ATTRIBUTE_NAME */
1213
1214           advance_to_name_end (context);
1215           add_to_partial (context, context->start, context->iter);
1216
1217           /* read the full name, if we enter the equals sign state
1218            * then add the attribute to the list (without the value),
1219            * otherwise store a partial chunk to be prepended later.
1220            */
1221           if (context->iter != context->current_text_end)
1222             context->state = STATE_AFTER_ATTRIBUTE_NAME;
1223           break;
1224
1225         case STATE_AFTER_ATTRIBUTE_NAME:
1226           /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1227
1228           skip_spaces (context);
1229
1230           if (context->iter != context->current_text_end)
1231             {
1232               /* The name has ended. Combine it with the partial chunk
1233                * if any; push it on the stack; enter next state.
1234                */
1235               add_attribute (context, g_string_free (context->partial_chunk, FALSE));
1236               
1237               context->partial_chunk = NULL;
1238               context->start = NULL;
1239               
1240               if (*context->iter == '=')
1241                 {
1242                   advance_char (context);
1243                   context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1244                 }
1245               else
1246                 {
1247                   gchar buf[8];
1248
1249                   set_error (context,
1250                              error,
1251                              G_MARKUP_ERROR_PARSE,
1252                              _("Odd character '%s', expected a '=' after "
1253                                "attribute name '%s' of element '%s'"),
1254                              utf8_str (context->iter, buf),
1255                              current_attribute (context),
1256                              current_element (context));
1257                   
1258                 }
1259             }
1260           break;
1261
1262         case STATE_BETWEEN_ATTRIBUTES:
1263           /* Possible next states: AFTER_CLOSE_ANGLE,
1264            * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1265            */
1266           skip_spaces (context);
1267
1268           if (context->iter != context->current_text_end)
1269             {
1270               if (*context->iter == '/')
1271                 {
1272                   advance_char (context);
1273                   context->state = STATE_AFTER_ELISION_SLASH;
1274                 }
1275               else if (*context->iter == '>')
1276                 {
1277
1278                   advance_char (context);
1279                   context->state = STATE_AFTER_CLOSE_ANGLE;
1280                 }
1281               else if (is_name_start_char (context->iter))
1282                 {
1283                   context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1284                   /* start of attribute name */
1285                   context->start = context->iter;
1286                 }
1287               else
1288                 {
1289                   gchar buf[8];
1290
1291                   set_error (context,
1292                              error,
1293                              G_MARKUP_ERROR_PARSE,
1294                              _("Odd character '%s', expected a '>' or '/' "
1295                                "character to end the start tag of "
1296                                "element '%s', or optionally an attribute; "
1297                                "perhaps you used an invalid character in "
1298                                "an attribute name"),
1299                              utf8_str (context->iter, buf),
1300                              current_element (context));
1301                 }
1302
1303               /* If we're done with attributes, invoke
1304                * the start_element callback
1305                */
1306               if (context->state == STATE_AFTER_ELISION_SLASH ||
1307                   context->state == STATE_AFTER_CLOSE_ANGLE)
1308                 {
1309                   const gchar *start_name;
1310                   /* Ugly, but the current code expects an empty array instead of NULL */
1311                   const gchar *empty = NULL;
1312                   const gchar **attr_names =  &empty;
1313                   const gchar **attr_values = &empty;
1314                   GError *tmp_error;
1315
1316                   /* Call user callback for element start */
1317                   start_name = current_element (context);
1318
1319                   if (context->cur_attr >= 0)
1320                     {
1321                       attr_names = (const gchar**)context->attr_names;
1322                       attr_values = (const gchar**)context->attr_values;
1323                     }
1324
1325                   tmp_error = NULL;
1326                   if (context->parser->start_element)
1327                     (* context->parser->start_element) (context,
1328                                                         start_name,
1329                                                         (const gchar **)attr_names,
1330                                                         (const gchar **)attr_values,
1331                                                         context->user_data,
1332                                                         &tmp_error);
1333
1334                   /* Go ahead and free the attributes. */
1335                   for (; context->cur_attr >= 0; context->cur_attr--)
1336                     {
1337                       int pos = context->cur_attr;
1338                       g_free (context->attr_names[pos]);
1339                       g_free (context->attr_values[pos]);
1340                       context->attr_names[pos] = context->attr_values[pos] = NULL;
1341                     }
1342                   g_assert (context->cur_attr == -1);
1343                   g_assert (context->attr_names == NULL ||
1344                             context->attr_names[0] == NULL);
1345                   g_assert (context->attr_values == NULL ||
1346                             context->attr_values[0] == NULL);
1347                   
1348                   if (tmp_error != NULL)
1349                     {
1350                       mark_error (context, tmp_error);
1351                       g_propagate_error (error, tmp_error);
1352                     }
1353                 }
1354             }
1355           break;
1356
1357         case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1358           /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1359
1360           skip_spaces (context);
1361
1362           if (context->iter != context->current_text_end)
1363             {
1364               if (*context->iter == '"')
1365                 {
1366                   advance_char (context);
1367                   context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1368                   context->start = context->iter;
1369                 }
1370               else if (*context->iter == '\'')
1371                 {
1372                   advance_char (context);
1373                   context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1374                   context->start = context->iter;
1375                 }
1376               else
1377                 {
1378                   gchar buf[8];
1379                   
1380                   set_error (context,
1381                              error,
1382                              G_MARKUP_ERROR_PARSE,
1383                              _("Odd character '%s', expected an open quote mark "
1384                                "after the equals sign when giving value for "
1385                                "attribute '%s' of element '%s'"),
1386                              utf8_str (context->iter, buf),
1387                              current_attribute (context),
1388                              current_element (context));
1389                 }
1390             }
1391           break;
1392
1393         case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1394         case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1395           /* Possible next states: BETWEEN_ATTRIBUTES */
1396           {
1397             gchar delim;
1398
1399             if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ) 
1400               {
1401                 delim = '\'';
1402               }
1403             else 
1404               {
1405                 delim = '"';
1406               }
1407
1408             do
1409               {
1410                 if (*context->iter == delim)
1411                   break;
1412               }
1413             while (advance_char (context));
1414           }
1415           if (context->iter == context->current_text_end)
1416             {
1417               /* The value hasn't necessarily ended. Merge with
1418                * partial chunk, leave state unchanged.
1419                */
1420               add_to_partial (context, context->start, context->iter);
1421             }
1422           else
1423             {
1424               /* The value has ended at the quote mark. Combine it
1425                * with the partial chunk if any; set it for the current
1426                * attribute.
1427                */
1428               GString *unescaped;
1429               
1430               add_to_partial (context, context->start, context->iter);
1431
1432               g_assert (context->cur_attr >= 0);
1433               
1434               if (unescape_text (context,
1435                                  context->partial_chunk->str,
1436                                  context->partial_chunk->str +
1437                                  context->partial_chunk->len,
1438                                  &unescaped,
1439                                  error))
1440                 {
1441                   /* success, advance past quote and set state. */
1442                   context->attr_values[context->cur_attr] = g_string_free (unescaped, FALSE);
1443                   advance_char (context);
1444                   context->state = STATE_BETWEEN_ATTRIBUTES;
1445                   context->start = NULL;
1446                 }
1447               
1448               truncate_partial (context);
1449             }
1450           break;
1451
1452         case STATE_INSIDE_TEXT:
1453           /* Possible next states: AFTER_OPEN_ANGLE */
1454           do
1455             {
1456               if (*context->iter == '<')
1457                 break;
1458             }
1459           while (advance_char (context));
1460
1461           /* The text hasn't necessarily ended. Merge with
1462            * partial chunk, leave state unchanged.
1463            */
1464
1465           add_to_partial (context, context->start, context->iter);
1466
1467           if (context->iter != context->current_text_end)
1468             {
1469               GString *unescaped = NULL;
1470
1471               /* The text has ended at the open angle. Call the text
1472                * callback.
1473                */
1474               
1475               if (unescape_text (context,
1476                                  context->partial_chunk->str,
1477                                  context->partial_chunk->str +
1478                                  context->partial_chunk->len,
1479                                  &unescaped,
1480                                  error))
1481                 {
1482                   GError *tmp_error = NULL;
1483
1484                   if (context->parser->text)
1485                     (*context->parser->text) (context,
1486                                               unescaped->str,
1487                                               unescaped->len,
1488                                               context->user_data,
1489                                               &tmp_error);
1490                   
1491                   g_string_free (unescaped, TRUE);
1492
1493                   if (tmp_error == NULL)
1494                     {
1495                       /* advance past open angle and set state. */
1496                       advance_char (context);
1497                       context->state = STATE_AFTER_OPEN_ANGLE;
1498                       /* could begin a passthrough */
1499                       context->start = context->iter;
1500                     }
1501                   else
1502                     {
1503                       mark_error (context, tmp_error);
1504                       g_propagate_error (error, tmp_error);
1505                     }
1506                 }
1507
1508               truncate_partial (context);
1509             }
1510           break;
1511
1512         case STATE_AFTER_CLOSE_TAG_SLASH:
1513           /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1514           if (is_name_start_char (context->iter))
1515             {
1516               context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1517
1518               /* start of tag name */
1519               context->start = context->iter;
1520             }
1521           else
1522             {
1523               gchar buf[8];
1524
1525               set_error (context,
1526                          error,
1527                          G_MARKUP_ERROR_PARSE,
1528                          _("'%s' is not a valid character following "
1529                            "the characters '</'; '%s' may not begin an "
1530                            "element name"),
1531                          utf8_str (context->iter, buf),
1532                          utf8_str (context->iter, buf));
1533             }
1534           break;
1535
1536         case STATE_INSIDE_CLOSE_TAG_NAME:
1537           /* Possible next state: AFTER_CLOSE_TAG_NAME */
1538           advance_to_name_end (context);
1539           add_to_partial (context, context->start, context->iter);
1540
1541           if (context->iter != context->current_text_end)
1542             context->state = STATE_AFTER_CLOSE_TAG_NAME;
1543           break;
1544
1545         case STATE_AFTER_CLOSE_TAG_NAME:
1546           /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1547
1548           skip_spaces (context);
1549           
1550           if (context->iter != context->current_text_end)
1551             {
1552               gchar *close_name;
1553
1554               /* The name has ended. Combine it with the partial chunk
1555                * if any; check that it matches stack top and pop
1556                * stack; invoke proper callback; enter next state.
1557                */
1558               close_name = g_string_free (context->partial_chunk, FALSE);
1559               context->partial_chunk = NULL;
1560               
1561               if (*context->iter != '>')
1562                 {
1563                   gchar buf[8];
1564
1565                   set_error (context,
1566                              error,
1567                              G_MARKUP_ERROR_PARSE,
1568                              _("'%s' is not a valid character following "
1569                                "the close element name '%s'; the allowed "
1570                                "character is '>'"),
1571                              utf8_str (context->iter, buf),
1572                              close_name);
1573                 }
1574               else if (context->tag_stack == NULL)
1575                 {
1576                   set_error (context,
1577                              error,
1578                              G_MARKUP_ERROR_PARSE,
1579                              _("Element '%s' was closed, no element "
1580                                "is currently open"),
1581                              close_name);
1582                 }
1583               else if (strcmp (close_name, current_element (context)) != 0)
1584                 {
1585                   set_error (context,
1586                              error,
1587                              G_MARKUP_ERROR_PARSE,
1588                              _("Element '%s' was closed, but the currently "
1589                                "open element is '%s'"),
1590                              close_name,
1591                              current_element (context));
1592                 }
1593               else
1594                 {
1595                   GError *tmp_error;
1596                   advance_char (context);
1597                   context->state = STATE_AFTER_CLOSE_ANGLE;
1598                   context->start = NULL;
1599                   
1600                   /* call the end_element callback */
1601                   tmp_error = NULL;
1602                   if (context->parser->end_element)
1603                     (* context->parser->end_element) (context,
1604                                                       close_name,
1605                                                       context->user_data,
1606                                                       &tmp_error);
1607                   
1608                   
1609                   /* Pop the tag stack */
1610                   g_free (context->tag_stack->data);
1611                   context->tag_stack = g_slist_delete_link (context->tag_stack,
1612                                                             context->tag_stack);
1613                   
1614                   if (tmp_error)
1615                     {
1616                       mark_error (context, tmp_error);
1617                       g_propagate_error (error, tmp_error);
1618                     }
1619                 }
1620               
1621               g_free (close_name);
1622             }
1623           break;
1624           
1625         case STATE_INSIDE_PASSTHROUGH:
1626           /* Possible next state: AFTER_CLOSE_ANGLE */
1627           do
1628             {
1629               if (*context->iter == '<') 
1630                 context->balance++;
1631               if (*context->iter == '>') 
1632                 {
1633                   context->balance--;
1634                   add_to_partial (context, context->start, context->iter);
1635                   context->start = context->iter;
1636                   if ((g_str_has_prefix (context->partial_chunk->str, "<?")
1637                        && g_str_has_suffix (context->partial_chunk->str, "?")) ||
1638                       (g_str_has_prefix (context->partial_chunk->str, "<!--")
1639                        && g_str_has_suffix (context->partial_chunk->str, "--")) ||
1640                       (g_str_has_prefix (context->partial_chunk->str, "<![CDATA[") 
1641                        && g_str_has_suffix (context->partial_chunk->str, "]]")) ||
1642                       (g_str_has_prefix (context->partial_chunk->str, "<!DOCTYPE")
1643                        && context->balance == 0)) 
1644                     break;
1645                 }
1646             }
1647           while (advance_char (context));
1648
1649           if (context->iter == context->current_text_end)
1650             {
1651               /* The passthrough hasn't necessarily ended. Merge with
1652                * partial chunk, leave state unchanged.
1653                */
1654               add_to_partial (context, context->start, context->iter);
1655             }
1656           else
1657             {
1658               /* The passthrough has ended at the close angle. Combine
1659                * it with the partial chunk if any. Call the passthrough
1660                * callback. Note that the open/close angles are
1661                * included in the text of the passthrough.
1662                */
1663               GError *tmp_error = NULL;
1664
1665               advance_char (context); /* advance past close angle */
1666               add_to_partial (context, context->start, context->iter);
1667
1668               if (context->parser->passthrough)
1669                 (*context->parser->passthrough) (context,
1670                                                  context->partial_chunk->str,
1671                                                  context->partial_chunk->len,
1672                                                  context->user_data,
1673                                                  &tmp_error);
1674                   
1675               truncate_partial (context);
1676
1677               if (tmp_error == NULL)
1678                 {
1679                   context->state = STATE_AFTER_CLOSE_ANGLE;
1680                   context->start = context->iter; /* could begin text */
1681                 }
1682               else
1683                 {
1684                   mark_error (context, tmp_error);
1685                   g_propagate_error (error, tmp_error);
1686                 }
1687             }
1688           break;
1689
1690         case STATE_ERROR:
1691           goto finished;
1692           break;
1693
1694         default:
1695           g_assert_not_reached ();
1696           break;
1697         }
1698     }
1699
1700  finished:
1701   context->parsing = FALSE;
1702
1703   return context->state != STATE_ERROR;
1704 }
1705
1706 /**
1707  * g_markup_parse_context_end_parse:
1708  * @context: a #GMarkupParseContext
1709  * @error: return location for a #GError
1710  * 
1711  * Signals to the #GMarkupParseContext that all data has been
1712  * fed into the parse context with g_markup_parse_context_parse().
1713  * This function reports an error if the document isn't complete,
1714  * for example if elements are still open.
1715  * 
1716  * Return value: %TRUE on success, %FALSE if an error was set
1717  **/
1718 gboolean
1719 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1720                                   GError             **error)
1721 {
1722   g_return_val_if_fail (context != NULL, FALSE);
1723   g_return_val_if_fail (!context->parsing, FALSE);
1724   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1725
1726   if (context->partial_chunk != NULL)
1727     {
1728       g_string_free (context->partial_chunk, TRUE);
1729       context->partial_chunk = NULL;
1730     }
1731
1732   if (context->document_empty)
1733     {
1734       set_error (context, error, G_MARKUP_ERROR_EMPTY,
1735                  _("Document was empty or contained only whitespace"));
1736       return FALSE;
1737     }
1738   
1739   context->parsing = TRUE;
1740   
1741   switch (context->state)
1742     {
1743     case STATE_START:
1744       /* Nothing to do */
1745       break;
1746
1747     case STATE_AFTER_OPEN_ANGLE:
1748       set_error (context, error, G_MARKUP_ERROR_PARSE,
1749                  _("Document ended unexpectedly just after an open angle bracket '<'"));
1750       break;
1751
1752     case STATE_AFTER_CLOSE_ANGLE:
1753       if (context->tag_stack != NULL)
1754         {
1755           /* Error message the same as for INSIDE_TEXT */
1756           set_error (context, error, G_MARKUP_ERROR_PARSE,
1757                      _("Document ended unexpectedly with elements still open - "
1758                        "'%s' was the last element opened"),
1759                      current_element (context));
1760         }
1761       break;
1762       
1763     case STATE_AFTER_ELISION_SLASH:
1764       set_error (context, error, G_MARKUP_ERROR_PARSE,
1765                  _("Document ended unexpectedly, expected to see a close angle "
1766                    "bracket ending the tag <%s/>"), current_element (context));
1767       break;
1768
1769     case STATE_INSIDE_OPEN_TAG_NAME:
1770       set_error (context, error, G_MARKUP_ERROR_PARSE,
1771                  _("Document ended unexpectedly inside an element name"));
1772       break;
1773
1774     case STATE_INSIDE_ATTRIBUTE_NAME:
1775       set_error (context, error, G_MARKUP_ERROR_PARSE,
1776                  _("Document ended unexpectedly inside an attribute name"));
1777       break;
1778
1779     case STATE_BETWEEN_ATTRIBUTES:
1780       set_error (context, error, G_MARKUP_ERROR_PARSE,
1781                  _("Document ended unexpectedly inside an element-opening "
1782                    "tag."));
1783       break;
1784
1785     case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1786       set_error (context, error, G_MARKUP_ERROR_PARSE,
1787                  _("Document ended unexpectedly after the equals sign "
1788                    "following an attribute name; no attribute value"));
1789       break;
1790
1791     case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1792     case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1793       set_error (context, error, G_MARKUP_ERROR_PARSE,
1794                  _("Document ended unexpectedly while inside an attribute "
1795                    "value"));
1796       break;
1797
1798     case STATE_INSIDE_TEXT:
1799       g_assert (context->tag_stack != NULL);
1800       set_error (context, error, G_MARKUP_ERROR_PARSE,
1801                  _("Document ended unexpectedly with elements still open - "
1802                    "'%s' was the last element opened"),
1803                  current_element (context));
1804       break;
1805
1806     case STATE_AFTER_CLOSE_TAG_SLASH:
1807     case STATE_INSIDE_CLOSE_TAG_NAME:
1808       set_error (context, error, G_MARKUP_ERROR_PARSE,
1809                  _("Document ended unexpectedly inside the close tag for "
1810                    "element '%s'"), current_element (context));
1811       break;
1812
1813     case STATE_INSIDE_PASSTHROUGH:
1814       set_error (context, error, G_MARKUP_ERROR_PARSE,
1815                  _("Document ended unexpectedly inside a comment or "
1816                    "processing instruction"));
1817       break;
1818
1819     case STATE_ERROR:
1820     default:
1821       g_assert_not_reached ();
1822       break;
1823     }
1824
1825   context->parsing = FALSE;
1826
1827   return context->state != STATE_ERROR;
1828 }
1829
1830 /**
1831  * g_markup_parse_context_get_element:
1832  * @context: a #GMarkupParseContext
1833  * @returns: the name of the currently open element, or %NULL
1834  *
1835  * Retrieves the name of the currently open element.
1836  *
1837  * Since: 2.2
1838  **/
1839 G_CONST_RETURN gchar *
1840 g_markup_parse_context_get_element (GMarkupParseContext *context)
1841 {
1842   g_return_val_if_fail (context != NULL, NULL);
1843
1844   if (context->tag_stack == NULL) 
1845     return NULL;
1846   else
1847     return current_element (context);
1848
1849
1850 /**
1851  * g_markup_parse_context_get_position:
1852  * @context: a #GMarkupParseContext
1853  * @line_number: return location for a line number, or %NULL
1854  * @char_number: return location for a char-on-line number, or %NULL
1855  *
1856  * Retrieves the current line number and the number of the character on
1857  * that line. Intended for use in error messages; there are no strict
1858  * semantics for what constitutes the "current" line number other than
1859  * "the best number we could come up with for error messages."
1860  * 
1861  **/
1862 void
1863 g_markup_parse_context_get_position (GMarkupParseContext *context,
1864                                      gint                *line_number,
1865                                      gint                *char_number)
1866 {
1867   g_return_if_fail (context != NULL);
1868
1869   if (line_number)
1870     *line_number = context->line_number;
1871
1872   if (char_number)
1873     *char_number = context->char_number;
1874 }
1875
1876 static void
1877 append_escaped_text (GString     *str,
1878                      const gchar *text,
1879                      gssize       length)    
1880 {
1881   const gchar *p;
1882   const gchar *end;
1883
1884   p = text;
1885   end = text + length;
1886
1887   while (p != end)
1888     {
1889       const gchar *next;
1890       next = g_utf8_next_char (p);
1891
1892       switch (*p)
1893         {
1894         case '&':
1895           g_string_append (str, "&amp;");
1896           break;
1897
1898         case '<':
1899           g_string_append (str, "&lt;");
1900           break;
1901
1902         case '>':
1903           g_string_append (str, "&gt;");
1904           break;
1905
1906         case '\'':
1907           g_string_append (str, "&apos;");
1908           break;
1909
1910         case '"':
1911           g_string_append (str, "&quot;");
1912           break;
1913
1914         default:
1915           g_string_append_len (str, p, next - p);
1916           break;
1917         }
1918
1919       p = next;
1920     }
1921 }
1922
1923 /**
1924  * g_markup_escape_text:
1925  * @text: some valid UTF-8 text
1926  * @length: length of @text in bytes
1927  * 
1928  * Escapes text so that the markup parser will parse it verbatim.
1929  * Less than, greater than, ampersand, etc. are replaced with the
1930  * corresponding entities. This function would typically be used
1931  * when writing out a file to be parsed with the markup parser.
1932  * 
1933  * Note that this function doesn't protect whitespace and line endings
1934  * from being processed according to the XML rules for normalization
1935  * of line endings and attribute values.
1936  * 
1937  * Return value: a newly allocated string with the escaped text
1938  **/
1939 gchar*
1940 g_markup_escape_text (const gchar *text,
1941                       gssize       length)  
1942 {
1943   GString *str;
1944
1945   g_return_val_if_fail (text != NULL, NULL);
1946
1947   if (length < 0)
1948     length = strlen (text);
1949
1950   /* prealloc at least as long as original text */
1951   str = g_string_sized_new (length);
1952   append_escaped_text (str, text, length);
1953
1954   return g_string_free (str, FALSE);
1955 }
1956
1957 /**
1958  * find_conversion:
1959  * @format: a printf-style format string
1960  * @after: location to store a pointer to the character after
1961  *   the returned conversion. On a %NULL return, returns the
1962  *   pointer to the trailing NUL in the string
1963  * 
1964  * Find the next conversion in a printf-style format string.
1965  * Partially based on code from printf-parser.c,
1966  * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
1967  * 
1968  * Return value: pointer to the next conversion in @format,
1969  *  or %NULL, if none.
1970  **/
1971 static const char *
1972 find_conversion (const char  *format,
1973                  const char **after)
1974 {
1975   const char *start = format;
1976   const char *cp;
1977   
1978   while (*start != '\0' && *start != '%')
1979     start++;
1980
1981   if (*start == '\0')
1982     {
1983       *after = start;
1984       return NULL;
1985     }
1986
1987   cp = start + 1;
1988
1989   if (*cp == '\0')
1990     {
1991       *after = cp;
1992       return NULL;
1993     }
1994   
1995   /* Test for positional argument.  */
1996   if (*cp >= '0' && *cp <= '9')
1997     {
1998       const char *np;
1999       
2000       for (np = cp; *np >= '0' && *np <= '9'; np++)
2001         ;
2002       if (*np == '$')
2003         cp = np + 1;
2004     }
2005
2006   /* Skip the flags.  */
2007   for (;;)
2008     {
2009       if (*cp == '\'' ||
2010           *cp == '-' ||
2011           *cp == '+' ||
2012           *cp == ' ' ||
2013           *cp == '#' ||
2014           *cp == '0')
2015         cp++;
2016       else
2017         break;
2018     }
2019
2020   /* Skip the field width.  */
2021   if (*cp == '*')
2022     {
2023       cp++;
2024
2025       /* Test for positional argument.  */
2026       if (*cp >= '0' && *cp <= '9')
2027         {
2028           const char *np;
2029
2030           for (np = cp; *np >= '0' && *np <= '9'; np++)
2031             ;
2032           if (*np == '$')
2033             cp = np + 1;
2034         }
2035     }
2036   else
2037     {
2038       for (; *cp >= '0' && *cp <= '9'; cp++)
2039         ;
2040     }
2041
2042   /* Skip the precision.  */
2043   if (*cp == '.')
2044     {
2045       cp++;
2046       if (*cp == '*')
2047         {
2048           /* Test for positional argument.  */
2049           if (*cp >= '0' && *cp <= '9')
2050             {
2051               const char *np;
2052
2053               for (np = cp; *np >= '0' && *np <= '9'; np++)
2054                 ;
2055               if (*np == '$')
2056                 cp = np + 1;
2057             }
2058         }
2059       else
2060         {
2061           for (; *cp >= '0' && *cp <= '9'; cp++)
2062             ;
2063         }
2064     }
2065
2066   /* Skip argument type/size specifiers.  */
2067   while (*cp == 'h' ||
2068          *cp == 'L' ||
2069          *cp == 'l' ||
2070          *cp == 'j' ||
2071          *cp == 'z' ||
2072          *cp == 'Z' ||
2073          *cp == 't')
2074     cp++;
2075           
2076   /* Skip the conversion character.  */
2077   cp++;
2078
2079   *after = cp;
2080   return start;
2081 }
2082
2083 /**
2084  * g_markup_vprintf_escaped:
2085  * @format: printf() style format string
2086  * @args: variable argument list, similar to vprintf()
2087  * 
2088  * Formats the data in @args according to @format, escaping
2089  * all string and character arguments in the fashion
2090  * of g_markup_escape_text(). See g_markup_printf_escaped().
2091  * 
2092  * Return value: newly allocated result from formatting
2093  *  operation. Free with g_free().
2094  *
2095  * Since: 2.4
2096  **/
2097 char *
2098 g_markup_vprintf_escaped (const char *format,
2099                           va_list     args)
2100 {
2101   GString *format1;
2102   GString *format2;
2103   GString *result = NULL;
2104   gchar *output1 = NULL;
2105   gchar *output2 = NULL;
2106   const char *p, *op1, *op2;
2107   va_list args2;
2108
2109   /* The technique here, is that we make two format strings that
2110    * have the identical conversions in the identical order to the
2111    * original strings, but differ in the text in-between. We
2112    * then use the normal g_strdup_vprintf() to format the arguments
2113    * with the two new format strings. By comparing the results,
2114    * we can figure out what segments of the output come from
2115    * the the original format string, and what from the arguments,
2116    * and thus know what portions of the string to escape.
2117    *
2118    * For instance, for:
2119    *
2120    *  g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2121    *
2122    * We form the two format strings "%sX%dX" and %sY%sY". The results
2123    * of formatting with those two strings are
2124    *
2125    * "%sX%dX" => "Susan & FredX5X"
2126    * "%sY%dY" => "Susan & FredY5Y"
2127    *
2128    * To find the span of the first argument, we find the first position
2129    * where the two arguments differ, which tells us that the first
2130    * argument formatted to "Susan & Fred". We then escape that
2131    * to "Susan &amp; Fred" and join up with the intermediate portions
2132    * of the format string and the second argument to get
2133    * "Susan &amp; Fred ate 5 apples".
2134    */
2135
2136   /* Create the two modified format strings
2137    */
2138   format1 = g_string_new (NULL);
2139   format2 = g_string_new (NULL);
2140   p = format;
2141   while (TRUE)
2142     {
2143       const char *after;
2144       const char *conv = find_conversion (p, &after);
2145       if (!conv)
2146         break;
2147
2148       g_string_append_len (format1, conv, after - conv);
2149       g_string_append_c (format1, 'X');
2150       g_string_append_len (format2, conv, after - conv);
2151       g_string_append_c (format2, 'Y');
2152
2153       p = after;
2154     }
2155
2156   /* Use them to format the arguments
2157    */
2158   G_VA_COPY (args2, args);
2159   
2160   output1 = g_strdup_vprintf (format1->str, args);
2161   va_end (args);
2162   if (!output1)
2163     goto cleanup;
2164   
2165   output2 = g_strdup_vprintf (format2->str, args2);
2166   va_end (args2);
2167   if (!output2)
2168     goto cleanup;
2169
2170   result = g_string_new (NULL);
2171
2172   /* Iterate through the original format string again,
2173    * copying the non-conversion portions and the escaped
2174    * converted arguments to the output string.
2175    */
2176   op1 = output1;
2177   op2 = output2;
2178   p = format;
2179   while (TRUE)
2180     {
2181       const char *after;
2182       const char *output_start;
2183       const char *conv = find_conversion (p, &after);
2184       char *escaped;
2185       
2186       if (!conv)        /* The end, after points to the trailing \0 */
2187         {
2188           g_string_append_len (result, p, after - p);
2189           break;
2190         }
2191
2192       g_string_append_len (result, p, conv - p);
2193       output_start = op1;
2194       while (*op1 == *op2)
2195         {
2196           op1++;
2197           op2++;
2198         }
2199       
2200       escaped = g_markup_escape_text (output_start, op1 - output_start);
2201       g_string_append (result, escaped);
2202       g_free (escaped);
2203       
2204       p = after;
2205       op1++;
2206       op2++;
2207     }
2208
2209  cleanup:
2210   g_string_free (format1, TRUE);
2211   g_string_free (format2, TRUE);
2212   g_free (output1);
2213   g_free (output2);
2214
2215   if (result)
2216     return g_string_free (result, FALSE);
2217   else
2218     return NULL;
2219 }
2220
2221 /**
2222  * g_markup_printf_escaped:
2223  * @format: printf() style format string
2224  * @Varargs: the arguments to insert in the format string
2225  * 
2226  * Formats arguments according to @format, escaping
2227  * all string and character arguments in the fashion
2228  * of g_markup_escape_text(). This is useful when you
2229  * want to insert literal strings into XML-style markup
2230  * output, without having to worry that the strings
2231  * might themselves contain markup.
2232  *
2233  * <informalexample><programlisting>
2234  * const char *store = "Fortnum &amp; Mason";
2235  * const char *item = "Tea";
2236  * char *output;
2237  * &nbsp;
2238  * output = g_markup_printf_escaped ("&lt;purchase&gt;"
2239  *                                   "&lt;store&gt;&percnt;s&lt;/store&gt;"
2240  *                                   "&lt;item&gt;&percnt;s&lt;/item&gt;"
2241  *                                   "&lt;/purchase&gt;",
2242  *                                   store, item);
2243  * </programlisting></informalexample>
2244  * 
2245  * Return value: newly allocated result from formatting
2246  *  operation. Free with g_free().
2247  *
2248  * Since: 2.4
2249  **/
2250 char *
2251 g_markup_printf_escaped (const char *format, ...)
2252 {
2253   char *result;
2254   va_list args;
2255   
2256   va_start (args, format);
2257   result = g_markup_vprintf_escaped (format, args);
2258   va_end (args);
2259
2260   return result;
2261 }
2262
2263 #define __G_MARKUP_C__
2264 #include "galiasdef.c"