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