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