inline docs (unescape_text): properly check strtoul for failure.
[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 /* 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           goto finished;
893         }
894     }
895
896   context->current_text = text;
897   context->current_text_len = text_len;
898   context->iter = context->current_text;
899   context->start = context->iter;
900
901   /* Nothing left after finishing the leftover char, or nothing
902    * passed in to begin with.
903    */
904   if (context->current_text_len == 0)
905     goto finished;
906
907   /* find_current_text_end () assumes the string starts at
908    * a character start, so we need to validate at least
909    * that much. It doesn't assume any following bytes
910    * are valid.
911    */
912   if ((*context->current_text & 0xc0) == 0x80) /* not a char start */
913     {
914       set_error (context,
915                  error,
916                  G_MARKUP_ERROR_BAD_UTF8,
917                  _("Invalid UTF-8 encoded text"));
918       goto finished;
919     }
920
921   /* Initialize context->current_text_end, possibly adjusting
922    * current_text_len, and add any leftover char portion
923    */
924   find_current_text_end (context);
925
926   /* Validate UTF8 (must be done after we find the end, since
927    * we could have a trailing incomplete char)
928    */
929   if (!g_utf8_validate (context->current_text,
930                         context->current_text_len,
931                         &first_invalid))
932     {
933       gint newlines = 0;
934       const gchar *p;
935       p = context->current_text;
936       while (p != context->current_text_end)
937         {
938           if (*p == '\n')
939             ++newlines;
940           ++p;
941         }
942
943       context->line_number += newlines;
944
945       set_error (context,
946                  error,
947                  G_MARKUP_ERROR_BAD_UTF8,
948                  _("Invalid UTF-8 encoded text"));
949       goto finished;
950     }
951
952   while (context->iter != context->current_text_end)
953     {
954       switch (context->state)
955         {
956         case STATE_START:
957           /* Possible next state: AFTER_OPEN_ANGLE */
958
959           g_assert (context->tag_stack == NULL);
960
961           /* whitespace is ignored outside of any elements */
962           skip_spaces (context);
963
964           if (context->iter != context->current_text_end)
965             {
966               if (*context->iter == '<')
967                 {
968                   /* Move after the open angle */
969                   advance_char (context);
970
971                   context->state = STATE_AFTER_OPEN_ANGLE;
972
973                   /* this could start a passthrough */
974                   context->start = context->iter;
975
976                   /* document is now non-empty */
977                   context->document_empty = FALSE;
978                 }
979               else
980                 {
981                   set_error (context,
982                              error,
983                              G_MARKUP_ERROR_PARSE,
984                              _("Document must begin with an element (e.g. <book>)"));
985                 }
986             }
987           break;
988
989         case STATE_AFTER_OPEN_ANGLE:
990           /* Possible next states: INSIDE_OPEN_TAG_NAME,
991            *  AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
992            */
993           if (*context->iter == '?' ||
994               *context->iter == '!')
995             {
996               /* include < in the passthrough */
997               const gchar *openangle = "<";
998               add_to_partial (context, openangle, openangle + 1);
999               context->start = context->iter;
1000               context->state = STATE_INSIDE_PASSTHROUGH;
1001             }
1002           else if (*context->iter == '/')
1003             {
1004               /* move after it */
1005               advance_char (context);
1006
1007               context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1008             }
1009           else if (is_name_start_char (g_utf8_get_char (context->iter)))
1010             {
1011               context->state = STATE_INSIDE_OPEN_TAG_NAME;
1012
1013               /* start of tag name */
1014               context->start = context->iter;
1015             }
1016           else
1017             {
1018               gchar buf[7];
1019               set_error (context,
1020                          error,
1021                          G_MARKUP_ERROR_PARSE,
1022                          _("'%s' is not a valid character following "
1023                            "a '<' character; it may not begin an "
1024                            "element name"),
1025                          utf8_str (context->iter, buf));
1026             }
1027           break;
1028
1029           /* The AFTER_CLOSE_ANGLE state is actually sort of
1030            * broken, because it doesn't correspond to a range
1031            * of characters in the input stream as the others do,
1032            * and thus makes things harder to conceptualize
1033            */
1034         case STATE_AFTER_CLOSE_ANGLE:
1035           /* Possible next states: INSIDE_TEXT, STATE_START */
1036           if (context->tag_stack == NULL)
1037             {
1038               context->start = NULL;
1039               context->state = STATE_START;
1040             }
1041           else
1042             {
1043               context->start = context->iter;
1044               context->state = STATE_INSIDE_TEXT;
1045             }
1046           break;
1047
1048         case STATE_AFTER_ELISION_SLASH:
1049           /* Possible next state: AFTER_CLOSE_ANGLE */
1050
1051           {
1052             /* We need to pop the tag stack and call the end_element
1053              * function, since this is the close tag
1054              */
1055             GError *tmp_error = NULL;
1056           
1057             g_assert (context->tag_stack != NULL);
1058
1059             tmp_error = NULL;
1060             if (context->parser->end_element)
1061               (* context->parser->end_element) (context,
1062                                                 context->tag_stack->data,
1063                                                 context->user_data,
1064                                                 &tmp_error);
1065           
1066             g_free (context->tag_stack->data);
1067             context->tag_stack = g_slist_delete_link (context->tag_stack,
1068                                                       context->tag_stack);
1069
1070             if (tmp_error)
1071               {
1072                 mark_error (context, tmp_error);
1073                 g_propagate_error (error, tmp_error);
1074               }          
1075             else
1076               {
1077                 if (*context->iter == '>')
1078                   {
1079                     /* move after the close angle */
1080                     advance_char (context);
1081                     context->state = STATE_AFTER_CLOSE_ANGLE;
1082                   }
1083                 else
1084                   {
1085                     gchar buf[7];
1086                     set_error (context,
1087                                error,
1088                                G_MARKUP_ERROR_PARSE,
1089                                _("Odd character '%s', expected a '>' character "
1090                                  "to end the start tag of element '%s'"),
1091                                utf8_str (context->iter, buf),
1092                                current_element (context));
1093                   }
1094               }
1095           }
1096           break;
1097
1098         case STATE_INSIDE_OPEN_TAG_NAME:
1099           /* Possible next states: BETWEEN_ATTRIBUTES */
1100
1101           /* if there's a partial chunk then it's the first part of the
1102            * tag name. If there's a context->start then it's the start
1103            * of the tag name in current_text, the partial chunk goes
1104            * before that start though.
1105            */
1106           advance_to_name_end (context);
1107
1108           if (context->iter == context->current_text_end)
1109             {
1110               /* The name hasn't necessarily ended. Merge with
1111                * partial chunk, leave state unchanged.
1112                */
1113               add_to_partial (context, context->start, context->iter);
1114             }
1115           else
1116             {
1117               /* The name has ended. Combine it with the partial chunk
1118                * if any; push it on the stack; enter next state.
1119                */
1120               add_to_partial (context, context->start, context->iter);
1121               context->tag_stack =
1122                 g_slist_prepend (context->tag_stack,
1123                                  g_string_free (context->partial_chunk,
1124                                                 FALSE));
1125
1126               context->partial_chunk = NULL;
1127
1128               context->state = STATE_BETWEEN_ATTRIBUTES;
1129               context->start = NULL;
1130             }
1131           break;
1132
1133         case STATE_INSIDE_ATTRIBUTE_NAME:
1134           /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1135
1136           /* read the full name, if we enter the equals sign state
1137            * then add the attribute to the list (without the value),
1138            * otherwise store a partial chunk to be prepended later.
1139            */
1140           advance_to_name_end (context);
1141
1142           if (context->iter == context->current_text_end)
1143             {
1144               /* The name hasn't necessarily ended. Merge with
1145                * partial chunk, leave state unchanged.
1146                */
1147               add_to_partial (context, context->start, context->iter);
1148             }
1149           else
1150             {
1151               /* The name has ended. Combine it with the partial chunk
1152                * if any; push it on the stack; enter next state.
1153                */
1154               GMarkupAttribute *attr;
1155               add_to_partial (context, context->start, context->iter);
1156
1157               attr = attribute_new (NULL, NULL);
1158
1159               attr->name = g_string_free (context->partial_chunk,
1160                                           FALSE);
1161
1162               context->partial_chunk = NULL;
1163               context->start = NULL;
1164
1165               context->attributes =
1166                 g_slist_prepend (context->attributes, attr);
1167
1168               if (*context->iter == '=')
1169                 {
1170                   advance_char (context);
1171                   context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1172                 }
1173               else
1174                 {
1175                   gchar buf[7];
1176                   set_error (context,
1177                              error,
1178                              G_MARKUP_ERROR_PARSE,
1179                              _("Odd character '%s', expected a '=' after "
1180                                "attribute name '%s' of element '%s'"),
1181                              utf8_str (context->iter, buf),
1182                              attr->name,
1183                              current_element (context));
1184
1185                 }
1186             }
1187           break;
1188
1189         case STATE_BETWEEN_ATTRIBUTES:
1190           /* Possible next states: AFTER_CLOSE_ANGLE,
1191            * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1192            */
1193           skip_spaces (context);
1194
1195           if (context->iter != context->current_text_end)
1196             {
1197               if (*context->iter == '/')
1198                 {
1199                   advance_char (context);
1200                   context->state = STATE_AFTER_ELISION_SLASH;
1201                 }
1202               else if (*context->iter == '>')
1203                 {
1204
1205                   advance_char (context);
1206                   context->state = STATE_AFTER_CLOSE_ANGLE;
1207                 }
1208               else if (is_name_start_char (g_utf8_get_char (context->iter)))
1209                 {
1210                   context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1211                   /* start of attribute name */
1212                   context->start = context->iter;
1213                 }
1214               else
1215                 {
1216                   gchar buf[7];
1217                   set_error (context,
1218                              error,
1219                              G_MARKUP_ERROR_PARSE,
1220                              _("Odd character '%s', expected a '>' or '/' "
1221                                "character to end the start tag of "
1222                                "element '%s', or optionally an attribute; "
1223                                "perhaps you used an invalid character in "
1224                                "an attribute name"),
1225                              utf8_str (context->iter, buf),
1226                              current_element (context));
1227                 }
1228
1229               /* If we're done with attributes, invoke
1230                * the start_element callback
1231                */
1232               if (context->state == STATE_AFTER_ELISION_SLASH ||
1233                   context->state == STATE_AFTER_CLOSE_ANGLE)
1234                 {
1235                   const gchar *start_name;
1236                   gchar **attr_names = NULL;
1237                   gchar **attr_values = NULL;
1238                   GError *tmp_error;
1239
1240                   /* Call user callback for element start */
1241                   start_name = current_element (context);
1242
1243                   /* this gratuituously copies the attr names/values
1244                    * I guess
1245                    */
1246                   attribute_list_to_arrays (context->attributes,
1247                                             &attr_names,
1248                                             &attr_values,
1249                                             NULL);
1250
1251                   tmp_error = NULL;
1252                   if (context->parser->start_element)
1253                     (* context->parser->start_element) (context,
1254                                                         start_name,
1255                                                         attr_names,
1256                                                         attr_values,
1257                                                         context->user_data,
1258                                                         &tmp_error);
1259
1260                   g_strfreev (attr_names);
1261                   g_strfreev (attr_values);
1262                   
1263                   /* Go ahead and free this. */
1264                   g_slist_foreach (context->attributes, (GFunc)attribute_free,
1265                                    NULL);
1266                   g_slist_free (context->attributes);
1267                   context->attributes = NULL;
1268
1269                   if (tmp_error != NULL)
1270                     {
1271                       mark_error (context, tmp_error);
1272                       g_propagate_error (error, tmp_error);
1273                     }
1274                 }
1275             }
1276           break;
1277
1278         case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1279           /* Possible next state: INSIDE_ATTRIBUTE_VALUE */
1280           if (*context->iter == '"')
1281             {
1282               advance_char (context);
1283               context->state = STATE_INSIDE_ATTRIBUTE_VALUE;
1284               context->start = context->iter;
1285             }
1286           else
1287             {
1288               gchar buf[7];
1289               set_error (context,
1290                          error,
1291                          G_MARKUP_ERROR_PARSE,
1292                          _("Odd character '%s', expected an open quote mark "
1293                            "after the equals sign when giving value for "
1294                            "attribute '%s' of element '%s'"),
1295                          utf8_str (context->iter, buf),
1296                          current_attribute (context),
1297                          current_element (context));
1298             }
1299           break;
1300
1301         case STATE_INSIDE_ATTRIBUTE_VALUE:
1302           /* Possible next states: BETWEEN_ATTRIBUTES */
1303           do
1304             {
1305               if (*context->iter == '"')
1306                 break;
1307             }
1308           while (advance_char (context));
1309
1310           if (context->iter == context->current_text_end)
1311             {
1312               /* The value hasn't necessarily ended. Merge with
1313                * partial chunk, leave state unchanged.
1314                */
1315               add_to_partial (context, context->start, context->iter);
1316             }
1317           else
1318             {
1319               /* The value has ended at the quote mark. Combine it
1320                * with the partial chunk if any; set it for the current
1321                * attribute.
1322                */
1323               GMarkupAttribute *attr;
1324
1325               add_to_partial (context, context->start, context->iter);
1326
1327               attr = context->attributes->data;
1328               
1329               if (unescape_text (context,
1330                                  context->partial_chunk->str,
1331                                  context->partial_chunk->str +
1332                                  context->partial_chunk->len,
1333                                  &attr->value,
1334                                  error))
1335                 {
1336                   /* success, advance past quote and set state. */
1337                   advance_char (context);
1338                   context->state = STATE_BETWEEN_ATTRIBUTES;
1339                   context->start = NULL;
1340                 }
1341               
1342               free_partial (context);
1343             }
1344           break;
1345
1346         case STATE_INSIDE_TEXT:
1347           /* Possible next states: AFTER_OPEN_ANGLE */
1348           do
1349             {
1350               if (*context->iter == '<')
1351                 break;
1352             }
1353           while (advance_char (context));
1354
1355           /* The text hasn't necessarily ended. Merge with
1356            * partial chunk, leave state unchanged.
1357            */
1358
1359           add_to_partial (context, context->start, context->iter);
1360
1361           if (context->iter != context->current_text_end)
1362             {
1363               gchar *unescaped = NULL;
1364
1365               /* The text has ended at the open angle. Call the text
1366                * callback.
1367                */
1368               
1369               if (unescape_text (context,
1370                                  context->partial_chunk->str,
1371                                  context->partial_chunk->str +
1372                                  context->partial_chunk->len,
1373                                  &unescaped,
1374                                  error))
1375                 {
1376                   GError *tmp_error = NULL;
1377
1378                   if (context->parser->text)
1379                     (*context->parser->text) (context,
1380                                               unescaped,
1381                                               strlen (unescaped),
1382                                               context->user_data,
1383                                               &tmp_error);
1384                   
1385                   g_free (unescaped);
1386
1387                   if (tmp_error == NULL)
1388                     {
1389                       /* advance past open angle and set state. */
1390                       advance_char (context);
1391                       context->state = STATE_AFTER_OPEN_ANGLE;
1392                       /* could begin a passthrough */
1393                       context->start = context->iter;
1394                     }
1395                   else
1396                     {
1397                       mark_error (context, tmp_error);
1398                       g_propagate_error (error, tmp_error);
1399                     }
1400                 }
1401
1402               free_partial (context);
1403             }
1404           break;
1405
1406         case STATE_AFTER_CLOSE_TAG_SLASH:
1407           /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1408           if (is_name_start_char (g_utf8_get_char (context->iter)))
1409             {
1410               context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1411
1412               /* start of tag name */
1413               context->start = context->iter;
1414             }
1415           else
1416             {
1417               gchar buf[7];
1418               set_error (context,
1419                          error,
1420                          G_MARKUP_ERROR_PARSE,
1421                          _("'%s' is not a valid character following "
1422                            "the characters '</'; '%s' may not begin an "
1423                            "element name"),
1424                          utf8_str (context->iter, buf),
1425                          utf8_str (context->iter, buf));
1426             }
1427           break;
1428
1429         case STATE_INSIDE_CLOSE_TAG_NAME:
1430           /* Possible next state: AFTER_CLOSE_ANGLE */
1431           advance_to_name_end (context);
1432
1433           if (context->iter == context->current_text_end)
1434             {
1435               /* The name hasn't necessarily ended. Merge with
1436                * partial chunk, leave state unchanged.
1437                */
1438               add_to_partial (context, context->start, context->iter);
1439             }
1440           else
1441             {
1442               /* The name has ended. Combine it with the partial chunk
1443                * if any; check that it matches stack top and pop
1444                * stack; invoke proper callback; enter next state.
1445                */
1446               gchar *close_name;
1447
1448               add_to_partial (context, context->start, context->iter);
1449
1450               close_name = g_string_free (context->partial_chunk, FALSE);
1451               context->partial_chunk = NULL;
1452               
1453               if (context->tag_stack == NULL)
1454                 {
1455                   set_error (context,
1456                              error,
1457                              G_MARKUP_ERROR_PARSE,
1458                              _("Element '%s' was closed, no element "
1459                                "is currently open"),
1460                              close_name);
1461                 }
1462               else if (strcmp (close_name, current_element (context)) != 0)
1463                 {
1464                   set_error (context,
1465                              error,
1466                              G_MARKUP_ERROR_PARSE,
1467                              _("Element '%s' was closed, but the currently "
1468                                "open element is '%s'"),
1469                              close_name,
1470                              current_element (context));
1471                 }
1472               else if (*context->iter != '>')
1473                 {
1474                   gchar buf[7];
1475                   set_error (context,
1476                              error,
1477                              G_MARKUP_ERROR_PARSE,
1478                              _("'%s' is not a valid character following "
1479                                "the close element name '%s'; the allowed "
1480                                "character is '>'"),
1481                              utf8_str (context->iter, buf),
1482                              close_name);
1483                 }
1484               else
1485                 {
1486                   GError *tmp_error;
1487                   advance_char (context);
1488                   context->state = STATE_AFTER_CLOSE_ANGLE;
1489                   context->start = NULL;
1490
1491                   /* call the end_element callback */
1492                   tmp_error = NULL;
1493                   if (context->parser->end_element)
1494                     (* context->parser->end_element) (context,
1495                                                       close_name,
1496                                                       context->user_data,
1497                                                       &tmp_error);
1498
1499                   
1500                   /* Pop the tag stack */
1501                   g_free (context->tag_stack->data);
1502                   context->tag_stack = g_slist_delete_link (context->tag_stack,
1503                                                             context->tag_stack);
1504                   
1505                   if (tmp_error)
1506                     {
1507                       mark_error (context, tmp_error);
1508                       g_propagate_error (error, tmp_error);
1509                     }
1510                 }
1511
1512               g_free (close_name);
1513             }
1514           break;
1515
1516         case STATE_INSIDE_PASSTHROUGH:
1517           /* Possible next state: AFTER_CLOSE_ANGLE */
1518           do
1519             {
1520               if (*context->iter == '>')
1521                 break;
1522             }
1523           while (advance_char (context));
1524
1525           if (context->iter == context->current_text_end)
1526             {
1527               /* The passthrough hasn't necessarily ended. Merge with
1528                * partial chunk, leave state unchanged.
1529                */
1530               add_to_partial (context, context->start, context->iter);
1531             }
1532           else
1533             {
1534               /* The passthrough has ended at the close angle. Combine
1535                * it with the partial chunk if any. Call the passthrough
1536                * callback. Note that the open/close angles are
1537                * included in the text of the passthrough.
1538                */
1539               GError *tmp_error = NULL;
1540
1541               advance_char (context); /* advance past close angle */
1542               add_to_partial (context, context->start, context->iter);
1543
1544               if (context->parser->passthrough)
1545                 (*context->parser->passthrough) (context,
1546                                                  context->partial_chunk->str,
1547                                                  context->partial_chunk->len,
1548                                                  context->user_data,
1549                                                  &tmp_error);
1550                   
1551               free_partial (context);
1552
1553               if (tmp_error == NULL)
1554                 {
1555                   context->state = STATE_AFTER_CLOSE_ANGLE;
1556                   context->start = context->iter; /* could begin text */
1557                 }
1558               else
1559                 {
1560                   mark_error (context, tmp_error);
1561                   g_propagate_error (error, tmp_error);
1562                 }
1563             }
1564           break;
1565
1566         case STATE_ERROR:
1567           goto finished;
1568           break;
1569
1570         default:
1571           g_assert_not_reached ();
1572           break;
1573         }
1574     }
1575
1576  finished:
1577   context->parsing = FALSE;
1578
1579   return context->state != STATE_ERROR;
1580 }
1581
1582 /**
1583  * g_markup_parse_context_end_parse:
1584  * @context: a #GMarkupParseContext
1585  * @error: return location for a #GError
1586  * 
1587  * Signals to the #GMarkupParseContext that all data has been
1588  * fed into the parse context with g_markup_parse_context_parse().
1589  * This function reports an error if the document isn't complete,
1590  * for example if elements are still open.
1591  * 
1592  * Return value: %TRUE on success, %FALSE if an error was set
1593  **/
1594 gboolean
1595 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1596                                   GError             **error)
1597 {
1598   g_return_val_if_fail (context != NULL, FALSE);
1599   g_return_val_if_fail (!context->parsing, FALSE);
1600   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1601
1602   if (context->document_empty)
1603     {
1604       set_error (context, error, G_MARKUP_ERROR_EMPTY,
1605                  _("Document was empty or contained only whitespace"));
1606       return FALSE;
1607     }
1608   
1609   context->parsing = TRUE;
1610   
1611   switch (context->state)
1612     {
1613     case STATE_START:
1614       /* Nothing to do */
1615       break;
1616
1617     case STATE_AFTER_OPEN_ANGLE:
1618       set_error (context, error, G_MARKUP_ERROR_PARSE,
1619                  _("Document ended unexpectedly just after an open angle bracket '<'"));
1620       break;
1621
1622     case STATE_AFTER_CLOSE_ANGLE:
1623       if (context->tag_stack != NULL)
1624         {
1625           /* Error message the same as for INSIDE_TEXT */
1626           set_error (context, error, G_MARKUP_ERROR_PARSE,
1627                      _("Document ended unexpectedly with elements still open - "
1628                        "'%s' was the last element opened"),
1629                      current_element (context));
1630         }
1631       break;
1632       
1633     case STATE_AFTER_ELISION_SLASH:
1634       set_error (context, error, G_MARKUP_ERROR_PARSE,
1635                  _("Document ended unexpectedly, expected to see a close angle "
1636                    "bracket ending the tag <%s/>"), current_element (context));
1637       break;
1638
1639     case STATE_INSIDE_OPEN_TAG_NAME:
1640       set_error (context, error, G_MARKUP_ERROR_PARSE,
1641                  _("Document ended unexpectedly inside an element name"));
1642       break;
1643
1644     case STATE_INSIDE_ATTRIBUTE_NAME:
1645       set_error (context, error, G_MARKUP_ERROR_PARSE,
1646                  _("Document ended unexpectedly inside an attribute name"));
1647       break;
1648
1649     case STATE_BETWEEN_ATTRIBUTES:
1650       set_error (context, error, G_MARKUP_ERROR_PARSE,
1651                  _("Document ended unexpectedly inside an element-opening "
1652                    "tag."));
1653       break;
1654
1655     case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1656       set_error (context, error, G_MARKUP_ERROR_PARSE,
1657                  _("Document ended unexpectedly after the equals sign "
1658                    "following an attribute name; no attribute value"));
1659       break;
1660
1661     case STATE_INSIDE_ATTRIBUTE_VALUE:
1662       set_error (context, error, G_MARKUP_ERROR_PARSE,
1663                  _("Document ended unexpectedly while inside an attribute "
1664                    "value"));
1665       break;
1666
1667     case STATE_INSIDE_TEXT:
1668       g_assert (context->tag_stack != NULL);
1669       set_error (context, error, G_MARKUP_ERROR_PARSE,
1670                  _("Document ended unexpectedly with elements still open - "
1671                    "'%s' was the last element opened"),
1672                  current_element (context));
1673       break;
1674
1675     case STATE_AFTER_CLOSE_TAG_SLASH:
1676     case STATE_INSIDE_CLOSE_TAG_NAME:
1677       set_error (context, error, G_MARKUP_ERROR_PARSE,
1678                  _("Document ended unexpectedly inside the close tag for"
1679                    "element '%s'"), current_element);
1680       break;
1681
1682     case STATE_INSIDE_PASSTHROUGH:
1683       set_error (context, error, G_MARKUP_ERROR_PARSE,
1684                  _("Document ended unexpectedly inside a comment or "
1685                    "processing instruction"));
1686       break;
1687
1688     case STATE_ERROR:
1689     default:
1690       g_assert_not_reached ();
1691       break;
1692     }
1693
1694   context->parsing = FALSE;
1695
1696   return context->state != STATE_ERROR;
1697 }
1698
1699 /**
1700  * g_markup_parse_context_get_position:
1701  * @context: a #GMarkupParseContext
1702  * @line_number: return location for a line number, or %NULL
1703  * @char_number: return location for a char-on-line number, or %NULL
1704  *
1705  * Returns the current line number and the number of the character on
1706  * that line. Intended for use in error messages; there are no strict
1707  * semantics for what constitutes the "current" line number other than
1708  * "the best number we could come up with for error messages."
1709  * 
1710  **/
1711 void
1712 g_markup_parse_context_get_position (GMarkupParseContext *context,
1713                                      gint                *line_number,
1714                                      gint                *char_number)
1715 {
1716   g_return_if_fail (context != NULL);
1717
1718   if (line_number)
1719     *line_number = context->line_number;
1720
1721   if (char_number)
1722     *char_number = context->char_number;
1723 }
1724
1725 static void
1726 append_escaped_text (GString     *str,
1727                      const gchar *text,
1728                      gint         length)
1729 {
1730   const gchar *p;
1731   const gchar *end;
1732
1733   p = text;
1734   end = text + length;
1735
1736   while (p != end)
1737     {
1738       const gchar *next;
1739       next = g_utf8_next_char (p);
1740
1741       switch (*p)
1742         {
1743         case '&':
1744           g_string_append (str, "&amp;");
1745           break;
1746
1747         case '<':
1748           g_string_append (str, "&lt;");
1749           break;
1750
1751         case '>':
1752           g_string_append (str, "&gt;");
1753           break;
1754
1755         case '\'':
1756           g_string_append (str, "&apos;");
1757           break;
1758
1759         case '"':
1760           g_string_append (str, "&quot;");
1761           break;
1762
1763         default:
1764           g_string_append_len (str, p, next - p);
1765           break;
1766         }
1767
1768       p = next;
1769     }
1770 }
1771
1772 /**
1773  * g_markup_escape_text:
1774  * @text: some valid UTF-8 text
1775  * @length: length of @text in bytes
1776  * 
1777  * Escapes text so that the markup parser will parse it verbatim.
1778  * Less than, greater than, ampersand, etc. are replaced with the
1779  * corresponding entities. This function would typically be used
1780  * when writing out a file to be parsed with the markup parser.
1781  * 
1782  * Return value: escaped text
1783  **/
1784 gchar*
1785 g_markup_escape_text (const gchar *text,
1786                       gint         length)
1787 {
1788   GString *str;
1789
1790   g_return_val_if_fail (text != NULL, NULL);
1791
1792   if (length < 0)
1793     length = strlen (text);
1794
1795   str = g_string_new ("");
1796   append_escaped_text (str, text, length);
1797
1798   return g_string_free (str, FALSE);
1799 }