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