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