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