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