remove debug spew
[platform/upstream/glib.git] / glib / gregex.c
1 /* GRegex -- regular expression API wrapper around PCRE.
2  *
3  * Copyright (C) 1999, 2000 Scott Wimer
4  * Copyright (C) 2004, Matthias Clasen <mclasen@redhat.com>
5  * Copyright (C) 2005 - 2007, Marco Barisione <marco@barisione.org>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include <config.h>
23
24 #include "gregex.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <string.h>
29
30 #ifdef USE_SYSTEM_PCRE
31 #include <pcre.h>
32 #else
33 #include "pcre/pcre.h"
34 #endif
35
36 #include "galias.h"
37
38 /* Mask of all the possible values for GRegexCompileFlags. */
39 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS          | \
40                               G_REGEX_MULTILINE         | \
41                               G_REGEX_DOTALL            | \
42                               G_REGEX_EXTENDED          | \
43                               G_REGEX_ANCHORED          | \
44                               G_REGEX_DOLLAR_ENDONLY    | \
45                               G_REGEX_UNGREEDY          | \
46                               G_REGEX_RAW               | \
47                               G_REGEX_NO_AUTO_CAPTURE   | \
48                               G_REGEX_OPTIMIZE          | \
49                               G_REGEX_DUPNAMES          | \
50                               G_REGEX_NEWLINE_CR        | \
51                               G_REGEX_NEWLINE_LF        | \
52                               G_REGEX_NEWLINE_CRLF)
53
54 /* Mask of all the possible values for GRegexMatchFlags. */
55 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED      | \
56                             G_REGEX_MATCH_NOTBOL        | \
57                             G_REGEX_MATCH_NOTEOL        | \
58                             G_REGEX_MATCH_NOTEMPTY      | \
59                             G_REGEX_MATCH_PARTIAL       | \
60                             G_REGEX_MATCH_NEWLINE_CR    | \
61                             G_REGEX_MATCH_NEWLINE_LF    | \
62                             G_REGEX_MATCH_NEWLINE_CRLF  | \
63                             G_REGEX_MATCH_NEWLINE_ANY)
64
65 /* if the string is in UTF-8 use g_utf8_ functions, else use
66  * use just +/- 1. */
67 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
68                                 g_utf8_next_char (s) : \
69                                 ((s) + 1))
70 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
71                                 g_utf8_prev_char (s) : \
72                                 ((s) - 1))
73
74 struct _GMatchInfo
75 {
76   GRegex *regex;                /* the regex */
77   GRegexMatchFlags match_opts;  /* options used at match time on the regex */
78   gint matches;                 /* number of matching sub patterns */
79   gint pos;                     /* position in the string where last match left off */
80   gint *offsets;                /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
81   gint n_offsets;               /* number of offsets */
82   gint *workspace;              /* workspace for pcre_dfa_exec() */
83   gint n_workspace;             /* number of workspace elements */
84   const gchar *string;          /* string passed to the match function */
85   gssize string_len;            /* length of string */
86 };
87
88 struct _GRegex
89 {
90   volatile guint ref_count;     /* the ref count for the immutable part */
91   gchar *pattern;               /* the pattern */
92   pcre *pcre_re;                /* compiled form of the pattern */
93   GRegexCompileFlags compile_opts;      /* options used at compile time on the pattern */
94   GRegexMatchFlags match_opts;  /* options used at match time on the regex */
95   pcre_extra *extra;            /* data stored when G_REGEX_OPTIMIZE is used */
96 };
97
98 /* TRUE if ret is an error code, FALSE otherwise. */
99 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
100
101 typedef struct _InterpolationData InterpolationData;
102 static gboolean  interpolation_list_needs_match (GList *list);
103 static gboolean  interpolate_replacement        (const GMatchInfo *match_info,
104                                                  GString *result,
105                                                  gpointer data);
106 static GList    *split_replacement              (const gchar *replacement,
107                                                  GError **error);
108 static void      free_interpolation_data        (InterpolationData *data);
109
110
111 static const gchar *
112 match_error (gint errcode)
113 {
114   switch (errcode)
115     {
116     case PCRE_ERROR_NOMATCH:
117       /* not an error */
118       break;
119     case PCRE_ERROR_NULL:
120       /* NULL argument, this should not happen in GRegex */
121       g_warning ("A NULL argument was passed to PCRE");
122       break;
123     case PCRE_ERROR_BADOPTION:
124       return "bad options";
125     case PCRE_ERROR_BADMAGIC:
126       return _("corrupted object");
127     case PCRE_ERROR_UNKNOWN_OPCODE:
128       return N_("internal error or corrupted object");
129     case PCRE_ERROR_NOMEMORY:
130       return _("out of memory");
131     case PCRE_ERROR_NOSUBSTRING:
132       /* not used by pcre_exec() */
133       break;
134     case PCRE_ERROR_MATCHLIMIT:
135       return _("backtracking limit reached");
136     case PCRE_ERROR_CALLOUT:
137       /* callouts are not implemented */
138       break;
139     case PCRE_ERROR_BADUTF8:
140     case PCRE_ERROR_BADUTF8_OFFSET:
141       /* we do not check if strings are valid */
142       break;
143     case PCRE_ERROR_PARTIAL:
144       /* not an error */
145       break;
146     case PCRE_ERROR_BADPARTIAL:
147       return _("the pattern contains items not supported for partial matching");
148     case PCRE_ERROR_INTERNAL:
149       return _("internal error");
150     case PCRE_ERROR_BADCOUNT:
151       /* negative ovecsize, this should not happen in GRegex */
152       g_warning ("A negative ovecsize was passed to PCRE");
153       break;
154     case PCRE_ERROR_DFA_UITEM:
155       return _("the pattern contains items not supported for partial matching");
156     case PCRE_ERROR_DFA_UCOND:
157       return _("back references as conditions are not supported for partial matching");
158     case PCRE_ERROR_DFA_UMLIMIT:
159       /* the match_field field is not used in GRegex */
160       break;
161     case PCRE_ERROR_DFA_WSSIZE:
162       /* handled expanding the workspace */
163       break;
164     case PCRE_ERROR_DFA_RECURSE:
165     case PCRE_ERROR_RECURSIONLIMIT:
166       return _("recursion limit reached");
167     case PCRE_ERROR_NULLWSLIMIT:
168       return _("workspace limit for empty substrings reached");
169     case PCRE_ERROR_BADNEWLINE:
170       return _("invalid combination of newline flags");
171     default:
172       break;
173     }
174   return _("unknown error");
175 }
176
177
178 /* GMatchInfo */
179
180 static GMatchInfo *
181 match_info_new (const GRegex *regex,
182                 const gchar  *string,
183                 gint          string_len,
184                 gint          start_position,
185                 gint          match_options,
186                 gboolean      is_dfa)
187 {
188   GMatchInfo *match_info;
189
190   if (string_len < 0)
191     string_len = strlen (string);
192
193   match_info = g_new0 (GMatchInfo, 1);
194   match_info->regex = g_regex_ref ((GRegex *)regex);
195   match_info->string = string;
196   match_info->string_len = string_len;
197   match_info->matches = PCRE_ERROR_NOMATCH;
198   match_info->pos = start_position;
199   match_info->match_opts = match_options;
200
201   if (is_dfa)
202     {
203       /* These values should be enough for most cases, if they are not
204        * enough g_regex_match_all_full() will expand them. */
205       match_info->n_offsets = 24;
206       match_info->n_workspace = 100;
207       match_info->workspace = g_new (gint, match_info->n_workspace);
208     }
209   else
210     {
211       gint capture_count;
212       pcre_fullinfo (regex->pcre_re, regex->extra,
213                      PCRE_INFO_CAPTURECOUNT, &capture_count);
214       match_info->n_offsets = (capture_count + 1) * 3;
215     }
216   match_info->offsets = g_new0 (gint, match_info->n_offsets);
217
218   return match_info;
219 }
220
221 /**
222  * g_match_info_get_regex:
223  * @match_info: a #GMatchInfo
224  *
225  * Returns #GRegex object used in @match_info. It belongs to Glib
226  * and must not be freed. Use g_regex_ref() if you need to keep it
227  * after you free @match_info object.
228  *
229  * Returns: #GRegex object used in @match_info
230  *
231  * Since: 2.14
232  */
233 GRegex *
234 g_match_info_get_regex (const GMatchInfo *match_info)
235 {
236   g_return_val_if_fail (match_info != NULL, NULL);
237   return match_info->regex;
238 }
239
240 /**
241  * g_match_info_get_string:
242  * @match_info: a #GMatchInfo
243  *
244  * Returns the string searched with @match_info. This is the
245  * string passed to g_regex_match() or g_regex_replace() so
246  * you may not free it before calling this function.
247  *
248  * Returns: the string searched with @match_info
249  *
250  * Since: 2.14
251  */
252 const gchar *
253 g_match_info_get_string (const GMatchInfo *match_info)
254 {
255   g_return_val_if_fail (match_info != NULL, NULL);
256   return match_info->string;
257 }
258
259 /**
260  * g_match_info_free:
261  * @match_info: a #GMatchInfo
262  *
263  * Frees all the memory associated with the #GMatchInfo structure.
264  *
265  * Since: 2.14
266  */
267 void
268 g_match_info_free (GMatchInfo *match_info)
269 {
270   if (match_info)
271     {
272       g_regex_unref (match_info->regex);
273       g_free (match_info->offsets);
274       g_free (match_info->workspace);
275       g_free (match_info);
276     }
277 }
278
279 /**
280  * g_match_info_next:
281  * @match_info: a #GMatchInfo structure
282  * @error: location to store the error occuring, or %NULL to ignore errors
283  *
284  * Scans for the next match using the same parameters of the previous
285  * call to g_regex_match_full() or g_regex_match() that returned
286  * @match_info.
287  *
288  * The match is done on the string passed to the match function, so you
289  * cannot free it before calling this function.
290  *
291  * Returns: %TRUE is the string matched, %FALSE otherwise
292  *
293  * Since: 2.14
294  */
295 gboolean
296 g_match_info_next (GMatchInfo  *match_info,
297                    GError     **error)
298 {
299   g_return_val_if_fail (match_info != NULL, FALSE);
300   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
301   g_return_val_if_fail (match_info->pos >= 0, FALSE);
302
303   gint opts = match_info->regex->match_opts | match_info->match_opts;
304  
305   match_info->matches = pcre_exec (match_info->regex->pcre_re,
306                                    match_info->regex->extra,
307                                    match_info->string,
308                                    match_info->string_len,
309                                    match_info->pos,
310                                    match_info->regex->match_opts |
311                                    match_info->match_opts,
312                                    match_info->offsets,
313                                    match_info->n_offsets);
314   if (IS_PCRE_ERROR (match_info->matches))
315     {
316       g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
317                    _("Error while matching regular expression %s: %s"),
318                    match_info->regex->pattern, match_error (match_info->matches));
319       return FALSE;
320     }
321
322   /* avoid infinite loops if the pattern is an empty string or something
323    * equivalent */
324   if (match_info->pos == match_info->offsets[1])
325     {
326       if (match_info->pos > match_info->string_len)
327         {
328           /* we have reached the end of the string */
329           match_info->pos = -1;
330           match_info->matches = PCRE_ERROR_NOMATCH;
331           return FALSE;
332         }
333
334       match_info->pos = NEXT_CHAR (match_info->regex,
335                                    &match_info->string[match_info->pos]) -
336                                    match_info->string;
337     }
338   else
339     {
340       match_info->pos = match_info->offsets[1];
341     }
342
343   return match_info->matches >= 0;
344 }
345
346 /**
347  * g_match_info_matches:
348  * @match_info: a #GMatchInfo structure
349  *
350  * Returns wether the previous match operation succeeded.
351  * 
352  * Returns: %TRUE if the previous match operation succeeded, 
353  *   %FALSE otherwise
354  *
355  * Since: 2.14
356  */
357 gboolean
358 g_match_info_matches (const GMatchInfo *match_info)
359 {
360   g_return_val_if_fail (match_info != NULL, FALSE);
361
362   return match_info->matches >= 0;
363 }
364
365 /**
366  * g_match_info_get_match_count:
367  * @match_info: a #GMatchInfo structure
368  *
369  * Retrieves the number of matched substrings (including substring 0, 
370  * that is the whole matched text), so 1 is returned if the pattern 
371  * has no substrings in it and 0 is returned if the match failed.
372  *
373  * If the last match was obtained using the DFA algorithm, that is 
374  * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
375  * count is not that of the number of capturing parentheses but that of
376  * the number of matched substrings.
377  *
378  * Returns: Number of matched substrings, or -1 if an error occurred
379  *
380  * Since: 2.14
381  */
382 gint
383 g_match_info_get_match_count (const GMatchInfo *match_info)
384 {
385   g_return_val_if_fail (match_info, -1);
386
387   if (match_info->matches == PCRE_ERROR_NOMATCH)
388     /* no match */
389     return 0;
390   else if (match_info->matches < PCRE_ERROR_NOMATCH)
391     /* error */
392     return -1;
393   else
394     /* match */
395     return match_info->matches;
396 }
397
398 /**
399  * g_match_info_is_partial_match:
400  * @match_info: a #GMatchInfo structure
401  *
402  * Usually if the string passed to g_regex_match*() matches as far as
403  * it goes, but is too short to match the entire pattern, %FALSE is
404  * returned. There are circumstances where it might be helpful to
405  * distinguish this case from other cases in which there is no match.
406  *
407  * Consider, for example, an application where a human is required to
408  * type in data for a field with specific formatting requirements. An
409  * example might be a date in the form ddmmmyy, defined by the pattern
410  * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
411  * If the application sees the user’s keystrokes one by one, and can
412  * check that what has been typed so far is potentially valid, it is
413  * able to raise an error as soon as a mistake is made.
414  *
415  * GRegex supports the concept of partial matching by means of the
416  * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
417  * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
418  * for a complete match, %FALSE otherwise. But, when these functions
419  * return %FALSE, you can check if the match was partial calling
420  * g_match_info_is_partial_match().
421  *
422  * When using partial matching you cannot use g_match_info_fetch*().
423  *
424  * Because of the way certain internal optimizations are implemented 
425  * the partial matching algorithm cannot be used with all patterns. 
426  * So repeated single characters such as "a{2,4}" and repeated single 
427  * meta-sequences such as "\d+" are not permitted if the maximum number 
428  * of occurrences is greater than one. Optional items such as "\d?" 
429  * (where the maximum is one) are permitted. Quantifiers with any values 
430  * are permitted after parentheses, so the invalid examples above can be 
431  * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set 
432  * for a pattern that does not conform to the restrictions, matching 
433  * functions return an error.
434  *
435  * Returns: %TRUE if the match was partial, %FALSE otherwise
436  *
437  * Since: 2.14
438  */
439 gboolean
440 g_match_info_is_partial_match (const GMatchInfo *match_info)
441 {
442   g_return_val_if_fail (match_info != NULL, FALSE);
443
444   return match_info->matches == PCRE_ERROR_PARTIAL;
445 }
446
447 /**
448  * g_match_info_expand_references:
449  * @match_info: a #GMatchInfo or %NULL
450  * @string_to_expand: the string to expand
451  * @error: location to store the error occuring, or %NULL to ignore errors
452  *
453  * Returns a new string containing the text in @string_to_expand with
454  * references and escape sequences expanded. References refer to the last
455  * match done with @string against @regex and have the same syntax used by
456  * g_regex_replace().
457  *
458  * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
459  * passed to g_regex_new().
460  *
461  * The backreferences are extracted from the string passed to the match
462  * function, so you cannot call this function after freeing the string.
463  *
464  * @match_info may be %NULL in which case @string_to_expand must not
465  * contain references. For instance "foo\n" does not refer to an actual
466  * pattern and '\n' merely will be replaced with \n character,
467  * while to expand "\0" (whole match) one needs the result of a match.
468  * Use g_regex_check_replacement() to find out whether @string_to_expand
469  * contains references.
470  *
471  * Returns: the expanded string, or %NULL if an error occurred
472  *
473  * Since: 2.14
474  */
475 gchar *
476 g_match_info_expand_references (const GMatchInfo  *match_info, 
477                                 const gchar       *string_to_expand,
478                                 GError           **error)
479 {
480   GString *result;
481   GList *list;
482   GError *tmp_error = NULL;
483
484   g_return_val_if_fail (string_to_expand != NULL, NULL);
485   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
486
487   list = split_replacement (string_to_expand, &tmp_error);
488   if (tmp_error != NULL)
489     {
490       g_propagate_error (error, tmp_error);
491       return NULL;
492     }
493
494   if (!match_info && interpolation_list_needs_match (list))
495     {
496       g_critical ("String '%s' contains references to the match, can't "
497                   "expand references without GMatchInfo object",
498                   string_to_expand);
499       return NULL;
500     }
501
502   result = g_string_sized_new (strlen (string_to_expand));
503   interpolate_replacement (match_info, result, list);
504
505   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
506   g_list_free (list);
507
508   return g_string_free (result, FALSE);
509 }
510
511 /**
512  * g_match_info_fetch:
513  * @match_info: #GMatchInfo structure
514  * @match_num: number of the sub expression
515  *
516  * Retrieves the text matching the @match_num<!-- -->'th capturing 
517  * parentheses. 0 is the full text of the match, 1 is the first paren 
518  * set, 2 the second, and so on.
519  *
520  * If @match_num is a valid sub pattern but it didn't match anything 
521  * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty 
522  * string is returned.
523  *
524  * If the match was obtained using the DFA algorithm, that is using
525  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
526  * string is not that of a set of parentheses but that of a matched
527  * substring. Substrings are matched in reverse order of length, so 
528  * 0 is the longest match.
529  *
530  * The string is fetched from the string passed to the match function,
531  * so you cannot call this function after freeing the string.
532  *
533  * Returns: The matched substring, or %NULL if an error occurred.
534  *          You have to free the string yourself
535  *
536  * Since: 2.14
537  */
538 gchar *
539 g_match_info_fetch (const GMatchInfo *match_info,
540                     gint              match_num)
541 {
542   /* we cannot use pcre_get_substring() because it allocates the
543    * string using pcre_malloc(). */
544   gchar *match = NULL;
545   gint start, end;
546
547   g_return_val_if_fail (match_info != NULL, NULL);
548   g_return_val_if_fail (match_num >= 0, NULL);
549
550   /* match_num does not exist or it didn't matched, i.e. matching "b"
551    * against "(a)?b" then group 0 is empty. */
552   if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
553     match = NULL;
554   else if (start == -1)
555     match = g_strdup ("");
556   else
557     match = g_strndup (&match_info->string[start], end - start);
558
559   return match;
560 }
561
562 /**
563  * g_match_info_fetch_pos:
564  * @match_info: #GMatchInfo structure
565  * @match_num: number of the sub expression
566  * @start_pos: pointer to location where to store the start position
567  * @end_pos: pointer to location where to store the end position
568  *
569  * Retrieves the position of the @match_num<!-- -->'th capturing 
570  * parentheses. 0 is the full text of the match, 1 is the first 
571  * paren set, 2 the second, and so on.
572  *
573  * If @match_num is a valid sub pattern but it didn't match anything 
574  * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos 
575  * and @end_pos are set to -1 and %TRUE is returned.
576  *
577  * If the match was obtained using the DFA algorithm, that is using
578  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
579  * position is not that of a set of parentheses but that of a matched
580  * substring. Substrings are matched in reverse order of length, so 
581  * 0 is the longest match.
582  *
583  * Returns: %TRUE if the position was fetched, %FALSE otherwise. If 
584  *   the position cannot be fetched, @start_pos and @end_pos are left 
585  *   unchanged
586  *
587  * Since: 2.14
588  */
589 gboolean
590 g_match_info_fetch_pos (const GMatchInfo *match_info,
591                         gint              match_num,
592                         gint             *start_pos,
593                         gint             *end_pos)
594 {
595   g_return_val_if_fail (match_info != NULL, FALSE);
596   g_return_val_if_fail (match_num >= 0, FALSE);
597  
598   /* make sure the sub expression number they're requesting is less than
599    * the total number of sub expressions that were matched. */
600   if (match_num >= match_info->matches)
601     return FALSE;
602
603   if (start_pos != NULL)
604     *start_pos = match_info->offsets[2 * match_num];
605
606   if (end_pos != NULL)
607     *end_pos = match_info->offsets[2 * match_num + 1];
608
609   return TRUE;
610 }
611
612 /*
613  * Returns number of first matched subpattern with name @name.
614  * There may be more than one in case when DUPNAMES is used,
615  * and not all subpatterns with that name match;
616  * pcre_get_stringnumber() does not work in that case.
617  */
618 static gint
619 get_matched_substring_number (const GMatchInfo *match_info,
620                               const gchar      *name)
621 {
622   gint entrysize;
623   gchar *first, *last;
624   guchar *entry;
625
626   /*
627    * FIXME: (?J) may be used inside the pattern as the equivalent of
628    * DUPNAMES compile option. In this case we can't know about it,
629    * and pcre doesn't tell us about it either, it uses private flag
630    * PCRE_JCHANGED for this. So we have to always search string
631    * table, unlike pcre which uses pcre_get_stringnumber() shortcut
632    * when possible. It shouldn't be actually bad since
633    * pcre_get_stringtable_entries() uses binary search; still would 
634    * be better to fix it, to be not worse than pcre.
635    */
636 #if 0
637   if ((match_info->regex->compile_opts & G_REGEX_DUPNAMES) == 0)
638     return pcre_get_stringnumber (match_info->regex->pcre_re, name);
639 #endif
640
641   /* This code is copied from pcre_get.c: get_first_set() */
642   entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re, 
643                                             name,
644                                             &first,
645                                             &last);
646
647   if (entrysize <= 0)
648     return entrysize;
649
650   for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
651     {
652       gint n = (entry[0] << 8) + entry[1];
653       if (match_info->offsets[n*2] >= 0)
654         return n;
655     }
656
657   return (first[0] << 8) + first[1];
658 }
659
660 /**
661  * g_match_info_fetch_named:
662  * @match_info: #GMatchInfo structure
663  * @name: name of the subexpression
664  *
665  * Retrieves the text matching the capturing parentheses named @name.
666  *
667  * If @name is a valid sub pattern name but it didn't match anything 
668  * (e.g. sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b") 
669  * then an empty string is returned.
670  *
671  * The string is fetched from the string passed to the match function,
672  * so you cannot call this function after freeing the string.
673  *
674  * Returns: The matched substring, or %NULL if an error occurred.
675  *          You have to free the string yourself
676  *
677  * Since: 2.14
678  */
679 gchar *
680 g_match_info_fetch_named (const GMatchInfo *match_info,
681                           const gchar      *name)
682 {
683   /* we cannot use pcre_get_named_substring() because it allocates the
684    * string using pcre_malloc(). */
685   gint num;
686
687   g_return_val_if_fail (match_info != NULL, NULL);
688   g_return_val_if_fail (name != NULL, NULL);
689
690   num = get_matched_substring_number (match_info, name);
691   if (num < 0)
692     return NULL;
693   else
694     return g_match_info_fetch (match_info, num);
695 }
696
697 /**
698  * g_match_info_fetch_named_pos:
699  * @match_info: #GMatchInfo structure
700  * @name: name of the subexpression
701  * @start_pos: pointer to location where to store the start position
702  * @end_pos: pointer to location where to store the end position
703  *
704  * Retrieves the position of the capturing parentheses named @name.
705  *
706  * If @name is a valid sub pattern name but it didn't match anything 
707  * (e.g. sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b") 
708  * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
709  *
710  * Returns: %TRUE if the position was fetched, %FALSE otherwise. If 
711  *   the position cannot be fetched, @start_pos and @end_pos are left
712  *   unchanged
713  *
714  * Since: 2.14
715  */
716 gboolean
717 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
718                               const gchar      *name,
719                               gint             *start_pos,
720                               gint             *end_pos)
721 {
722   gint num;
723
724   g_return_val_if_fail (match_info != NULL, FALSE);
725   g_return_val_if_fail (name != NULL, FALSE);
726
727   num = get_matched_substring_number (match_info, name);
728   if (num < 0)
729     return FALSE;
730
731   return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
732 }
733
734 /**
735  * g_match_info_fetch_all:
736  * @match_info: a #GMatchInfo structure
737  *
738  * Bundles up pointers to each of the matching substrings from a match
739  * and stores them in an array of gchar pointers. The first element in
740  * the returned array is the match number 0, i.e. the entire matched
741  * text.
742  *
743  * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
744  * "b" against "(a)?b") then an empty string is inserted.
745  *
746  * If the last match was obtained using the DFA algorithm, that is using
747  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
748  * strings are not that matched by sets of parentheses but that of the
749  * matched substring. Substrings are matched in reverse order of length,
750  * so the first one is the longest match.
751  *
752  * The strings are fetched from the string passed to the match function,
753  * so you cannot call this function after freeing the string.
754  *
755  * Returns: a %NULL-terminated array of gchar * pointers. It must be 
756  *   freed using g_strfreev(). If the previous match failed %NULL is
757  *   returned
758  *
759  * Since: 2.14
760  */
761 gchar **
762 g_match_info_fetch_all (const GMatchInfo *match_info)
763 {
764   /* we cannot use pcre_get_substring_list() because the returned value
765    * isn't suitable for g_strfreev(). */
766   gchar **result;
767   gint i;
768
769   g_return_val_if_fail (match_info != NULL, FALSE);
770
771   if (match_info->matches < 0)
772     return NULL;
773
774   result = g_new (gchar *, match_info->matches + 1);
775   for (i = 0; i < match_info->matches; i++)
776     result[i] = g_match_info_fetch (match_info, i);
777   result[i] = NULL;
778
779   return result;
780 }
781
782
783 /* GRegex */
784
785 GQuark
786 g_regex_error_quark (void)
787 {
788   static GQuark error_quark = 0;
789
790   if (error_quark == 0)
791     error_quark = g_quark_from_static_string ("g-regex-error-quark");
792
793   return error_quark;
794 }
795
796 /**
797  * g_regex_ref:
798  * @regex: a #GRegex
799  *
800  * Increases reference count of @regex by 1.
801  *
802  * Returns: @regex
803  *
804  * Since: 2.14
805  */
806 GRegex *
807 g_regex_ref (GRegex *regex)
808 {
809   g_return_val_if_fail (regex != NULL, NULL);
810   g_atomic_int_inc ((gint*) &regex->ref_count);
811   return regex;
812 }
813
814 /**
815  * g_regex_unref:
816  * @regex: a #GRegex
817  *
818  * Decreases reference count of @regex by 1. When reference count drops
819  * to zero, it frees all the memory associated with the regex structure.
820  *
821  * Since: 2.14
822  */
823 void
824 g_regex_unref (GRegex *regex)
825 {
826   g_return_if_fail (regex != NULL);
827
828   if (g_atomic_int_exchange_and_add ((gint *) &regex->ref_count, -1) - 1 == 0)
829     {
830       g_free (regex->pattern);
831       if (regex->pcre_re != NULL)
832         pcre_free (regex->pcre_re);
833       if (regex->extra != NULL)
834         pcre_free (regex->extra);
835       g_free (regex);
836     }
837 }
838
839 /** 
840  * g_regex_new:
841  * @pattern: the regular expression
842  * @compile_options: compile options for the regular expression
843  * @match_options: match options for the regular expression
844  * @error: return location for a #GError
845  * 
846  * Compiles the regular expression to an internal form, and does 
847  * the initial setup of the #GRegex structure.  
848  * 
849  * Returns: a #GRegex structure. Call g_regex_unref() when you 
850  *   are done with it
851  *
852  * Since: 2.14
853  */
854 GRegex *
855 g_regex_new (const gchar         *pattern, 
856              GRegexCompileFlags   compile_options,
857              GRegexMatchFlags     match_options,
858              GError             **error)
859 {
860   GRegex *regex;
861   pcre *re;
862   const gchar *errmsg;
863   gint erroffset;
864   gboolean optimize = FALSE;
865   static gboolean initialized = FALSE;
866   
867   g_return_val_if_fail (pattern != NULL, NULL);
868   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
869   g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
870   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
871
872   if (!initialized)
873     {
874       gint support;
875       const gchar *msg;
876
877       pcre_config (PCRE_CONFIG_UTF8, &support);
878       if (!support)
879         {
880           msg = N_("PCRE library is compiled without UTF8 support");
881           g_critical (msg);
882           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
883           return NULL;
884         }
885
886       pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
887       if (!support)
888         {
889           msg = N_("PCRE library is compiled without UTF8 properties support");
890           g_critical (msg);
891           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
892           return NULL;
893         }
894
895       initialized = TRUE;
896     }
897
898   /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
899    * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
900   if (compile_options & G_REGEX_OPTIMIZE)
901     optimize = TRUE;
902
903   /* In GRegex the string are, by default, UTF-8 encoded. PCRE
904    * instead uses UTF-8 only if required with PCRE_UTF8. */
905   if (compile_options & G_REGEX_RAW)
906     {
907       /* disable utf-8 */
908       compile_options &= ~G_REGEX_RAW;
909     }
910   else
911     {
912       /* enable utf-8 */
913       compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
914       match_options |= PCRE_NO_UTF8_CHECK;
915     }
916
917   /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
918    * not for the system one. */
919   if (!(compile_options & G_REGEX_NEWLINE_CR) &&
920       !(compile_options & G_REGEX_NEWLINE_LF))
921     {
922       compile_options |= PCRE_NEWLINE_ANY;
923     }
924
925   /* compile the pattern */
926   re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
927
928   /* if the compilation failed, set the error member and return 
929    * immediately */
930   if (re == NULL)
931     {
932       GError *tmp_error = g_error_new (G_REGEX_ERROR, 
933                                        G_REGEX_ERROR_COMPILE,
934                                        _("Error while compiling regular "
935                                          "expression %s at char %d: %s"),
936                                        pattern, erroffset, errmsg);
937       g_propagate_error (error, tmp_error);
938
939       return NULL;
940     }
941
942   regex = g_new0 (GRegex, 1);
943   regex->ref_count = 1;
944   regex->pattern = g_strdup (pattern);
945   regex->pcre_re = re;
946   regex->compile_opts = compile_options;
947   regex->match_opts = match_options;
948
949   if (optimize)
950     {
951       regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
952       if (errmsg != NULL)
953         {
954           GError *tmp_error = g_error_new (G_REGEX_ERROR,
955                                            G_REGEX_ERROR_OPTIMIZE, 
956                                            _("Error while optimizing "
957                                              "regular expression %s: %s"),
958                                            regex->pattern,
959                                            errmsg);
960           g_propagate_error (error, tmp_error);
961           return NULL;
962         }
963     }
964
965   return regex;
966 }
967
968 /**
969  * g_regex_get_pattern:
970  * @regex: a #GRegex structure
971  *
972  * Gets the pattern string associated with @regex, i.e. a copy of 
973  * the string passed to g_regex_new().
974  *
975  * Returns: the pattern of @regex
976  *
977  * Since: 2.14
978  */
979 const gchar *
980 g_regex_get_pattern (const GRegex *regex)
981 {
982   g_return_val_if_fail (regex != NULL, NULL);
983
984   return regex->pattern;
985 }
986
987 /**
988  * g_regex_get_max_backref:
989  * @regex: a #GRegex
990  *  
991  * Returns the number of the highest back reference
992  * in the pattern, or 0 if the pattern does not contain
993  * back references.
994  *
995  * Returns: the number of the highest back reference
996  *
997  * Since: 2.14
998  */
999 gint
1000 g_regex_get_max_backref (const GRegex *regex)
1001 {
1002   gint value;
1003
1004   pcre_fullinfo (regex->pcre_re, regex->extra,
1005                  PCRE_INFO_BACKREFMAX, &value);
1006
1007   return value;
1008 }
1009
1010 /**
1011  * g_regex_get_capture_count:
1012  * @regex: a #GRegex
1013  *
1014  * Returns the number of capturing subpatterns in the pattern.
1015  *
1016  * Returns: the number of capturing subpatterns
1017  *
1018  * Since: 2.14
1019  */
1020 gint
1021 g_regex_get_capture_count (const GRegex *regex)
1022 {
1023   gint value;
1024
1025   pcre_fullinfo (regex->pcre_re, regex->extra,
1026                  PCRE_INFO_CAPTURECOUNT, &value);
1027
1028   return value;
1029 }
1030
1031 /**
1032  * g_regex_match_simple:
1033  * @pattern: the regular expression
1034  * @string: the string to scan for matches
1035  * @compile_options: compile options for the regular expression
1036  * @match_options: match options
1037  *
1038  * Scans for a match in @string for @pattern.
1039  *
1040  * This function is equivalent to g_regex_match() but it does not
1041  * require to compile the pattern with g_regex_new(), avoiding some
1042  * lines of code when you need just to do a match without extracting
1043  * substrings, capture counts, and so on.
1044  *
1045  * If this function is to be called on the same @pattern more than
1046  * once, it's more efficient to compile the pattern once with
1047  * g_regex_new() and then use g_regex_match().
1048  *
1049  * Returns: %TRUE is the string matched, %FALSE otherwise
1050  *
1051  * Since: 2.14
1052  */
1053 gboolean
1054 g_regex_match_simple (const gchar        *pattern, 
1055                       const gchar        *string, 
1056                       GRegexCompileFlags  compile_options,
1057                       GRegexMatchFlags    match_options)
1058 {
1059   GRegex *regex;
1060   gboolean result;
1061
1062   regex = g_regex_new (pattern, compile_options, 0, NULL);
1063   if (!regex)
1064     return FALSE;
1065   result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1066   g_regex_unref (regex);
1067   return result;
1068 }
1069
1070 /**
1071  * g_regex_match:
1072  * @regex: a #GRegex structure from g_regex_new()
1073  * @string: the string to scan for matches
1074  * @match_options: match options
1075  * @match_info: pointer to location where to store the #GMatchInfo, 
1076  *   or %NULL if you do not need it
1077  *
1078  * Scans for a match in string for the pattern in @regex. 
1079  * The @match_options are combined with the match options specified 
1080  * when the @regex structure was created, letting you have more 
1081  * flexibility in reusing #GRegex structures.
1082  *
1083  * A #GMatchInfo structure, used to get information on the match, 
1084  * is stored in @match_info if not %NULL. Note that if @match_info 
1085  * is not %NULL then it is created even if the function returns %FALSE, 
1086  * i.e. you must free it regardless if regular expression actually matched.
1087  *
1088  * To retrieve all the non-overlapping matches of the pattern in 
1089  * string you can use g_match_info_next().
1090  *
1091  * <informalexample><programlisting>
1092  * static void
1093  * print_uppercase_words (const gchar *string)
1094  * {
1095  *   /&ast; Print all uppercase-only words. &ast;/
1096  *   GRegex *regex;
1097  *   GMatchInfo *match_info;
1098  *   &nbsp;
1099  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1100  *   g_regex_match (regex, string, 0, &amp;match_info);
1101  *   while (g_match_info_matches (match_info))
1102  *     {
1103  *       gchar *word = g_match_info_fetch (match_info, 0);
1104  *       g_print ("Found: %s\n", word);
1105  *       g_free (word);
1106  *       g_match_info_next (match_info, NULL);
1107  *     }
1108  *   g_match_info_free (match_info);
1109  *   g_regex_unref (regex);
1110  * }
1111  * </programlisting></informalexample>
1112  *
1113  * Returns: %TRUE is the string matched, %FALSE otherwise
1114  *
1115  * Since: 2.14
1116  */
1117 gboolean
1118 g_regex_match (const GRegex      *regex, 
1119                const gchar       *string, 
1120                GRegexMatchFlags   match_options,
1121                GMatchInfo       **match_info)
1122 {
1123   return g_regex_match_full (regex, string, -1, 0, match_options,
1124                              match_info, NULL);
1125 }
1126
1127 /**
1128  * g_regex_match_full:
1129  * @regex: a #GRegex structure from g_regex_new()
1130  * @string: the string to scan for matches
1131  * @string_len: the length of @string, or -1 if @string is nul-terminated
1132  * @start_position: starting index of the string to match
1133  * @match_options: match options
1134  * @match_info: pointer to location where to store the #GMatchInfo, 
1135  *   or %NULL if you do not need it
1136  * @error: location to store the error occuring, or %NULL to ignore errors
1137  *
1138  * Scans for a match in string for the pattern in @regex. 
1139  * The @match_options are combined with the match options specified 
1140  * when the @regex structure was created, letting you have more 
1141  * flexibility in reusing #GRegex structures.
1142  *
1143  * Setting @start_position differs from just passing over a shortened 
1144  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1145  * that begins with any kind of lookbehind assertion, such as "\b".
1146  *
1147  * A #GMatchInfo structure, used to get information on the match, is 
1148  * stored in @match_info if not %NULL. Note that if @match_info is 
1149  * not %NULL then it is created even if the function returns %FALSE, 
1150  * i.e. you must free it regardless if regular expression actually 
1151  * matched.
1152  *
1153  * @string is not copied and is used in #GMatchInfo internally. If 
1154  * you use any #GMatchInfo method (except g_match_info_free()) after 
1155  * freeing or modifying @string then the behaviour is undefined.
1156  *
1157  * To retrieve all the non-overlapping matches of the pattern in 
1158  * string you can use g_match_info_next().
1159  *
1160  * <informalexample><programlisting>
1161  * static void
1162  * print_uppercase_words (const gchar *string)
1163  * {
1164  *   /&ast; Print all uppercase-only words. &ast;/
1165  *   GRegex *regex;
1166  *   GMatchInfo *match_info;
1167  *   GError *error = NULL;
1168  *   &nbsp;
1169  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1170  *   g_regex_match_full (regex, string, -1, 0, 0, &amp;match_info, &amp;error);
1171  *   while (g_match_info_matches (match_info))
1172  *     {
1173  *       gchar *word = g_match_info_fetch (match_info, 0);
1174  *       g_print ("Found: %s\n", word);
1175  *       g_free (word);
1176  *       g_match_info_next (match_info, &amp;error);
1177  *     }
1178  *   g_match_info_free (match_info);
1179  *   g_regex_unref (regex);
1180  *   if (error != NULL)
1181  *     {
1182  *       g_printerr ("Error while matching: %s\n", error->message);
1183  *       g_error_free (error);
1184  *     }
1185  * }
1186  * </programlisting></informalexample>
1187  *
1188  * Returns: %TRUE is the string matched, %FALSE otherwise
1189  *
1190  * Since: 2.14
1191  */
1192 gboolean
1193 g_regex_match_full (const GRegex      *regex,
1194                     const gchar       *string,
1195                     gssize             string_len,
1196                     gint               start_position,
1197                     GRegexMatchFlags   match_options,
1198                     GMatchInfo       **match_info,
1199                     GError           **error)
1200 {
1201   GMatchInfo *info;
1202   gboolean match_ok;
1203
1204   g_return_val_if_fail (regex != NULL, FALSE);
1205   g_return_val_if_fail (string != NULL, FALSE);
1206   g_return_val_if_fail (start_position >= 0, FALSE);
1207   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1208   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1209
1210   info = match_info_new (regex, string, string_len, start_position,
1211                          match_options, FALSE);
1212   match_ok = g_match_info_next (info, error);
1213   if (match_info != NULL)
1214     *match_info = info;
1215   else
1216     g_match_info_free (info);
1217
1218   return match_ok;
1219 }
1220
1221 /**
1222  * g_regex_match_all:
1223  * @regex: a #GRegex structure from g_regex_new()
1224  * @string: the string to scan for matches
1225  * @match_options: match options
1226  * @match_info: pointer to location where to store the #GMatchInfo, 
1227  *   or %NULL if you do not need it
1228  *
1229  * Using the standard algorithm for regular expression matching only 
1230  * the longest match in the string is retrieved. This function uses 
1231  * a different algorithm so it can retrieve all the possible matches.
1232  * For more documentation see g_regex_match_all_full().
1233  *
1234  * A #GMatchInfo structure, used to get information on the match, is 
1235  * stored in @match_info if not %NULL. Note that if @match_info is 
1236  * not %NULL then it is created even if the function returns %FALSE, 
1237  * i.e. you must free it regardless if regular expression actually 
1238  * matched.
1239  *
1240  * Returns: %TRUE is the string matched, %FALSE otherwise
1241  *
1242  * Since: 2.14
1243  */
1244 gboolean
1245 g_regex_match_all (const GRegex      *regex,
1246                    const gchar       *string,
1247                    GRegexMatchFlags   match_options,
1248                    GMatchInfo       **match_info)
1249 {
1250   return g_regex_match_all_full (regex, string, -1, 0, match_options,
1251                                  match_info, NULL);
1252 }
1253
1254 /**
1255  * g_regex_match_all_full:
1256  * @regex: a #GRegex structure from g_regex_new()
1257  * @string: the string to scan for matches
1258  * @string_len: the length of @string, or -1 if @string is nul-terminated
1259  * @start_position: starting index of the string to match
1260  * @match_options: match options
1261  * @match_info: pointer to location where to store the #GMatchInfo, 
1262  *   or %NULL if you do not need it
1263  * @error: location to store the error occuring, or %NULL to ignore errors
1264  *
1265  * Using the standard algorithm for regular expression matching only 
1266  * the longest match in the string is retrieved, it is not possibile 
1267  * to obtain all the available matches. For instance matching
1268  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;" 
1269  * you get "&lt;a&gt; &lt;b&gt; &lt;c&gt;".
1270  *
1271  * This function uses a different algorithm (called DFA, i.e. deterministic
1272  * finite automaton), so it can retrieve all the possible matches, all
1273  * starting at the same point in the string. For instance matching
1274  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;" 
1275  * you would obtain three matches: "&lt;a&gt; &lt;b&gt; &lt;c&gt;",
1276  * "&lt;a&gt; &lt;b&gt;" and "&lt;a&gt;".
1277  *
1278  * The number of matched strings is retrieved using
1279  * g_match_info_get_match_count(). To obtain the matched strings and 
1280  * their position you can use, respectively, g_match_info_fetch() and 
1281  * g_match_info_fetch_pos(). Note that the strings are returned in 
1282  * reverse order of length; that is, the longest matching string is 
1283  * given first.
1284  *
1285  * Note that the DFA algorithm is slower than the standard one and it 
1286  * is not able to capture substrings, so backreferences do not work.
1287  *
1288  * Setting @start_position differs from just passing over a shortened 
1289  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1290  * that begins with any kind of lookbehind assertion, such as "\b".
1291  *
1292  * A #GMatchInfo structure, used to get information on the match, is 
1293  * stored in @match_info if not %NULL. Note that if @match_info is 
1294  * not %NULL then it is created even if the function returns %FALSE, 
1295  * i.e. you must free it regardless if regular expression actually 
1296  * matched.
1297  *
1298  * Returns: %TRUE is the string matched, %FALSE otherwise
1299  *
1300  * Since: 2.14
1301  */
1302 gboolean
1303 g_regex_match_all_full (const GRegex      *regex,
1304                         const gchar       *string,
1305                         gssize             string_len,
1306                         gint               start_position,
1307                         GRegexMatchFlags   match_options,
1308                         GMatchInfo       **match_info,
1309                         GError           **error)
1310 {
1311   GMatchInfo *info;
1312   gboolean done;
1313
1314   g_return_val_if_fail (regex != NULL, FALSE);
1315   g_return_val_if_fail (string != NULL, FALSE);
1316   g_return_val_if_fail (start_position >= 0, FALSE);
1317   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1318   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1319
1320   info = match_info_new (regex, string, string_len, start_position,
1321                          match_options, TRUE);
1322
1323   done = FALSE;
1324   while (!done)
1325     {
1326       done = TRUE;
1327       info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1328                                      info->string, info->string_len,
1329                                      info->pos,
1330                                      regex->match_opts | match_options,
1331                                      info->offsets, info->n_offsets,
1332                                      info->workspace, info->n_workspace);
1333       if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1334         {
1335           /* info->workspace is too small. */
1336           info->n_workspace *= 2;
1337           info->workspace = g_realloc (info->workspace,
1338                                        info->n_workspace * sizeof (gint));
1339           done = FALSE;
1340         }
1341       else if (info->matches == 0)
1342         {
1343           /* info->offsets is too small. */
1344           info->n_offsets *= 2;
1345           info->offsets = g_realloc (info->offsets,
1346                                      info->n_offsets * sizeof (gint));
1347           done = FALSE;
1348         }
1349       else if (IS_PCRE_ERROR (info->matches))
1350         {
1351           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1352                        _("Error while matching regular expression %s: %s"),
1353                        regex->pattern, match_error (info->matches));
1354         }
1355     }
1356
1357   /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1358   info->pos = -1;
1359
1360   if (match_info != NULL)
1361     *match_info = info;
1362   else
1363     g_match_info_free (info);
1364
1365   return info->matches >= 0;
1366 }
1367
1368 /**
1369  * g_regex_get_string_number:
1370  * @regex: #GRegex structure
1371  * @name: name of the subexpression
1372  *
1373  * Retrieves the number of the subexpression named @name.
1374  *
1375  * Returns: The number of the subexpression or -1 if @name 
1376  *   does not exists
1377  *
1378  * Since: 2.14
1379  */
1380 gint
1381 g_regex_get_string_number (const GRegex *regex,
1382                            const gchar  *name)
1383 {
1384   gint num;
1385
1386   g_return_val_if_fail (regex != NULL, -1);
1387   g_return_val_if_fail (name != NULL, -1);
1388
1389   num = pcre_get_stringnumber (regex->pcre_re, name);
1390   if (num == PCRE_ERROR_NOSUBSTRING)
1391     num = -1;
1392
1393   return num;
1394 }
1395
1396 /**
1397  * g_regex_split_simple:
1398  * @pattern: the regular expression
1399  * @string: the string to scan for matches
1400  * @compile_options: compile options for the regular expression
1401  * @match_options: match options
1402  *
1403  * Breaks the string on the pattern, and returns an array of 
1404  * the tokens. If the pattern contains capturing parentheses, 
1405  * then the text for each of the substrings will also be returned. 
1406  * If the pattern does not match anywhere in the string, then the 
1407  * whole string is returned as the first token.
1408  *
1409  * This function is equivalent to g_regex_split() but it does 
1410  * not require to compile the pattern with g_regex_new(), avoiding 
1411  * some lines of code when you need just to do a split without 
1412  * extracting substrings, capture counts, and so on.
1413  *
1414  * If this function is to be called on the same @pattern more than
1415  * once, it's more efficient to compile the pattern once with
1416  * g_regex_new() and then use g_regex_split().
1417  *
1418  * As a special case, the result of splitting the empty string "" 
1419  * is an empty vector, not a vector containing a single string. 
1420  * The reason for this special case is that being able to represent 
1421  * a empty vector is typically more useful than consistent handling 
1422  * of empty elements. If you do need to represent empty elements, 
1423  * you'll need to check for the empty string before calling this 
1424  * function.
1425  *
1426  * A pattern that can match empty strings splits @string into 
1427  * separate characters wherever it matches the empty string between 
1428  * characters. For example splitting "ab c" using as a separator 
1429  * "\s*", you will get "a", "b" and "c".
1430  *
1431  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1432  *
1433  * Since: 2.14
1434  **/
1435 gchar **
1436 g_regex_split_simple (const gchar        *pattern,
1437                       const gchar        *string, 
1438                       GRegexCompileFlags  compile_options,
1439                       GRegexMatchFlags    match_options)
1440 {
1441   GRegex *regex;
1442   gchar **result;
1443
1444   regex = g_regex_new (pattern, compile_options, 0, NULL);
1445   if (!regex)
1446     return NULL;
1447   result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1448   g_regex_unref (regex);
1449   return result;
1450 }
1451
1452 /**
1453  * g_regex_split:
1454  * @regex: a #GRegex structure
1455  * @string: the string to split with the pattern
1456  * @match_options: match time option flags
1457  *
1458  * Breaks the string on the pattern, and returns an array of the tokens.
1459  * If the pattern contains capturing parentheses, then the text for each
1460  * of the substrings will also be returned. If the pattern does not match
1461  * anywhere in the string, then the whole string is returned as the first
1462  * token.
1463  *
1464  * As a special case, the result of splitting the empty string "" is an
1465  * empty vector, not a vector containing a single string. The reason for
1466  * this special case is that being able to represent a empty vector is
1467  * typically more useful than consistent handling of empty elements. If
1468  * you do need to represent empty elements, you'll need to check for the
1469  * empty string before calling this function.
1470  *
1471  * A pattern that can match empty strings splits @string into separate
1472  * characters wherever it matches the empty string between characters.
1473  * For example splitting "ab c" using as a separator "\s*", you will get
1474  * "a", "b" and "c".
1475  *
1476  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1477  *
1478  * Since: 2.14
1479  **/
1480 gchar **
1481 g_regex_split (const GRegex     *regex, 
1482                const gchar      *string, 
1483                GRegexMatchFlags  match_options)
1484 {
1485   return g_regex_split_full (regex, string, -1, 0,
1486                              match_options, 0, NULL);
1487 }
1488
1489 /**
1490  * g_regex_split_full:
1491  * @regex: a #GRegex structure
1492  * @string: the string to split with the pattern
1493  * @string_len: the length of @string, or -1 if @string is nul-terminated
1494  * @start_position: starting index of the string to match
1495  * @match_options: match time option flags
1496  * @max_tokens: the maximum number of tokens to split @string into. 
1497  *   If this is less than 1, the string is split completely
1498  * @error: return location for a #GError
1499  *
1500  * Breaks the string on the pattern, and returns an array of the tokens.
1501  * If the pattern contains capturing parentheses, then the text for each
1502  * of the substrings will also be returned. If the pattern does not match
1503  * anywhere in the string, then the whole string is returned as the first
1504  * token.
1505  *
1506  * As a special case, the result of splitting the empty string "" is an
1507  * empty vector, not a vector containing a single string. The reason for
1508  * this special case is that being able to represent a empty vector is
1509  * typically more useful than consistent handling of empty elements. If
1510  * you do need to represent empty elements, you'll need to check for the
1511  * empty string before calling this function.
1512  *
1513  * A pattern that can match empty strings splits @string into separate
1514  * characters wherever it matches the empty string between characters.
1515  * For example splitting "ab c" using as a separator "\s*", you will get
1516  * "a", "b" and "c".
1517  *
1518  * Setting @start_position differs from just passing over a shortened 
1519  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1520  * that begins with any kind of lookbehind assertion, such as "\b".
1521  *
1522  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1523  *
1524  * Since: 2.14
1525  **/
1526 gchar **
1527 g_regex_split_full (const GRegex      *regex, 
1528                     const gchar       *string, 
1529                     gssize             string_len,
1530                     gint               start_position,
1531                     GRegexMatchFlags   match_options,
1532                     gint               max_tokens,
1533                     GError           **error)
1534 {
1535   GError *tmp_error = NULL;
1536   GMatchInfo *match_info;
1537   GList *list, *last;
1538   gint i;
1539   gint token_count;
1540   gboolean match_ok;
1541   /* position of the last separator. */
1542   gint last_separator_end;
1543   /* was the last match 0 bytes long? */
1544   gboolean last_match_is_empty;
1545   /* the returned array of char **s */
1546   gchar **string_list;
1547
1548   g_return_val_if_fail (regex != NULL, NULL);
1549   g_return_val_if_fail (string != NULL, NULL);
1550   g_return_val_if_fail (start_position >= 0, NULL);
1551   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1552   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1553
1554   if (max_tokens <= 0)
1555     max_tokens = G_MAXINT;
1556
1557   if (string_len < 0)
1558     string_len = strlen (string);
1559
1560   /* zero-length string */
1561   if (string_len - start_position == 0)
1562     return g_new0 (gchar *, 1);
1563
1564   if (max_tokens == 1)
1565     {
1566       string_list = g_new0 (gchar *, 2);
1567       string_list[0] = g_strndup (&string[start_position],
1568                                   string_len - start_position);
1569       return string_list;
1570     }
1571
1572   list = NULL;
1573   token_count = 0;
1574   last_separator_end = start_position;
1575   last_match_is_empty = FALSE;
1576
1577   match_ok = g_regex_match_full (regex, string, string_len, start_position,
1578                                  match_options, &match_info, &tmp_error);
1579   while (tmp_error == NULL)
1580     {
1581       if (match_ok)
1582         {
1583           last_match_is_empty =
1584                     (match_info->offsets[0] == match_info->offsets[1]);
1585
1586           /* we need to skip empty separators at the same position of the end
1587            * of another separator. e.g. the string is "a b" and the separator
1588            * is " *", so from 1 to 2 we have a match and at position 2 we have
1589            * an empty match. */
1590           if (last_separator_end != match_info->offsets[1])
1591             {
1592               gchar *token;
1593               gint match_count;
1594
1595               token = g_strndup (string + last_separator_end,
1596                                  match_info->offsets[0] - last_separator_end);
1597               list = g_list_prepend (list, token);
1598               token_count++;
1599
1600               /* if there were substrings, these need to be added to
1601                * the list. */
1602               match_count = g_match_info_get_match_count (match_info);
1603               if (match_count > 1)
1604                 {
1605                   for (i = 1; i < match_count; i++)
1606                     list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1607                 }
1608             }
1609         }
1610       else
1611         {
1612           /* if there was no match, copy to end of string. */
1613           if (!last_match_is_empty)
1614             {
1615               gchar *token = g_strndup (string + last_separator_end,
1616                                         match_info->string_len - last_separator_end);
1617               list = g_list_prepend (list, token);
1618             }
1619           /* no more tokens, end the loop. */
1620           break;
1621         }
1622
1623       /* -1 to leave room for the last part. */
1624       if (token_count >= max_tokens - 1)
1625         {
1626           /* we have reached the maximum number of tokens, so we copy
1627            * the remaining part of the string. */
1628           if (last_match_is_empty)
1629             {
1630               /* the last match was empty, so we have moved one char
1631                * after the real position to avoid empty matches at the
1632                * same position. */
1633               match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1634             }
1635           /* the if is needed in the case we have terminated the available
1636            * tokens, but we are at the end of the string, so there are no
1637            * characters left to copy. */
1638           if (string_len > match_info->pos)
1639             {
1640               gchar *token = g_strndup (string + match_info->pos,
1641                                         string_len - match_info->pos);
1642               list = g_list_prepend (list, token);
1643             }
1644           /* end the loop. */
1645           break;
1646         }
1647
1648       last_separator_end = match_info->pos;
1649       if (last_match_is_empty)
1650         /* if the last match was empty, g_match_info_next() has moved
1651          * forward to avoid infinite loops, but we still need to copy that
1652          * character. */
1653         last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1654
1655       match_ok = g_match_info_next (match_info, &tmp_error);
1656     }
1657   g_match_info_free (match_info);
1658   if (tmp_error != NULL)
1659     {
1660       g_propagate_error (error, tmp_error);
1661       g_list_foreach (list, (GFunc)g_free, NULL);
1662       g_list_free (list);
1663       match_info->pos = -1;
1664       return NULL;
1665     }
1666
1667   string_list = g_new (gchar *, g_list_length (list) + 1);
1668   i = 0;
1669   for (last = g_list_last (list); last; last = g_list_previous (last))
1670     string_list[i++] = last->data;
1671   string_list[i] = 0;
1672   g_list_free (list);
1673
1674   return string_list;
1675 }
1676
1677 enum
1678 {
1679   REPL_TYPE_STRING,
1680   REPL_TYPE_CHARACTER,
1681   REPL_TYPE_SYMBOLIC_REFERENCE,
1682   REPL_TYPE_NUMERIC_REFERENCE,
1683   REPL_TYPE_CHANGE_CASE
1684 }; 
1685
1686 typedef enum
1687 {
1688   CHANGE_CASE_NONE         = 1 << 0,
1689   CHANGE_CASE_UPPER        = 1 << 1,
1690   CHANGE_CASE_LOWER        = 1 << 2,
1691   CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1692   CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1693   CHANGE_CASE_SINGLE_MASK  = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1694   CHANGE_CASE_LOWER_MASK   = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1695   CHANGE_CASE_UPPER_MASK   = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1696 } ChangeCase;
1697
1698 struct _InterpolationData
1699 {
1700   gchar     *text;   
1701   gint       type;   
1702   gint       num;
1703   gchar      c;
1704   ChangeCase change_case;
1705 };
1706
1707 static void
1708 free_interpolation_data (InterpolationData *data)
1709 {
1710   g_free (data->text);
1711   g_free (data);
1712 }
1713
1714 static const gchar *
1715 expand_escape (const gchar        *replacement,
1716                const gchar        *p, 
1717                InterpolationData  *data,
1718                GError            **error)
1719 {
1720   const gchar *q, *r;
1721   gint x, d, h, i;
1722   const gchar *error_detail;
1723   gint base = 0;
1724   GError *tmp_error = NULL;
1725
1726   p++;
1727   switch (*p)
1728     {
1729     case 't':
1730       p++;
1731       data->c = '\t';
1732       data->type = REPL_TYPE_CHARACTER;
1733       break;
1734     case 'n':
1735       p++;
1736       data->c = '\n';
1737       data->type = REPL_TYPE_CHARACTER;
1738       break;
1739     case 'v':
1740       p++;
1741       data->c = '\v';
1742       data->type = REPL_TYPE_CHARACTER;
1743       break;
1744     case 'r':
1745       p++;
1746       data->c = '\r';
1747       data->type = REPL_TYPE_CHARACTER;
1748       break;
1749     case 'f':
1750       p++;
1751       data->c = '\f';
1752       data->type = REPL_TYPE_CHARACTER;
1753       break;
1754     case 'a':
1755       p++;
1756       data->c = '\a';
1757       data->type = REPL_TYPE_CHARACTER;
1758       break;
1759     case 'b':
1760       p++;
1761       data->c = '\b';
1762       data->type = REPL_TYPE_CHARACTER;
1763       break;
1764     case '\\':
1765       p++;
1766       data->c = '\\';
1767       data->type = REPL_TYPE_CHARACTER;
1768       break;
1769     case 'x':
1770       p++;
1771       x = 0;
1772       if (*p == '{')
1773         {
1774           p++;
1775           do 
1776             {
1777               h = g_ascii_xdigit_value (*p);
1778               if (h < 0)
1779                 {
1780                   error_detail = _("hexadecimal digit or '}' expected");
1781                   goto error;
1782                 }
1783               x = x * 16 + h;
1784               p++;
1785             }
1786           while (*p != '}');
1787           p++;
1788         }
1789       else
1790         {
1791           for (i = 0; i < 2; i++)
1792             {
1793               h = g_ascii_xdigit_value (*p);
1794               if (h < 0)
1795                 {
1796                   error_detail = _("hexadecimal digit expected");
1797                   goto error;
1798                 }
1799               x = x * 16 + h;
1800               p++;
1801             }
1802         }
1803       data->type = REPL_TYPE_STRING;
1804       data->text = g_new0 (gchar, 8);
1805       g_unichar_to_utf8 (x, data->text);
1806       break;
1807     case 'l':
1808       p++;
1809       data->type = REPL_TYPE_CHANGE_CASE;
1810       data->change_case = CHANGE_CASE_LOWER_SINGLE;
1811       break;
1812     case 'u':
1813       p++;
1814       data->type = REPL_TYPE_CHANGE_CASE;
1815       data->change_case = CHANGE_CASE_UPPER_SINGLE;
1816       break;
1817     case 'L':
1818       p++;
1819       data->type = REPL_TYPE_CHANGE_CASE;
1820       data->change_case = CHANGE_CASE_LOWER;
1821       break;
1822     case 'U':
1823       p++;
1824       data->type = REPL_TYPE_CHANGE_CASE;
1825       data->change_case = CHANGE_CASE_UPPER;
1826       break;
1827     case 'E':
1828       p++;
1829       data->type = REPL_TYPE_CHANGE_CASE;
1830       data->change_case = CHANGE_CASE_NONE;
1831       break;
1832     case 'g':
1833       p++;
1834       if (*p != '<')
1835         {
1836           error_detail = _("missing '<' in symbolic reference");
1837           goto error;
1838         }
1839       q = p + 1;
1840       do 
1841         {
1842           p++;
1843           if (!*p)
1844             {
1845               error_detail = _("unfinished symbolic reference");
1846               goto error;
1847             }
1848         }
1849       while (*p != '>');
1850       if (p - q == 0)
1851         {
1852           error_detail = _("zero-length symbolic reference");
1853           goto error;
1854         }
1855       if (g_ascii_isdigit (*q))
1856         {
1857           x = 0;
1858           do 
1859             {
1860               h = g_ascii_digit_value (*q);
1861               if (h < 0)
1862                 {
1863                   error_detail = _("digit expected");
1864                   p = q;
1865                   goto error;
1866                 }
1867               x = x * 10 + h;
1868               q++;
1869             }
1870           while (q != p);
1871           data->num = x;
1872           data->type = REPL_TYPE_NUMERIC_REFERENCE;
1873         }
1874       else
1875         {
1876           r = q;
1877           do 
1878             {
1879               if (!g_ascii_isalnum (*r))
1880                 {
1881                   error_detail = _("illegal symbolic reference");
1882                   p = r;
1883                   goto error;
1884                 }
1885               r++;
1886             }
1887           while (r != p);
1888           data->text = g_strndup (q, p - q);
1889           data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1890         }
1891       p++;
1892       break;
1893     case '0':
1894       /* if \0 is followed by a number is an octal number representing a
1895        * character, else it is a numeric reference. */
1896       if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1897         {
1898           base = 8;
1899           p = g_utf8_next_char (p);
1900         }
1901     case '1':
1902     case '2':
1903     case '3':
1904     case '4':
1905     case '5':
1906     case '6':
1907     case '7':
1908     case '8':
1909     case '9':
1910       x = 0;
1911       d = 0;
1912       for (i = 0; i < 3; i++)
1913         {
1914           h = g_ascii_digit_value (*p);
1915           if (h < 0) 
1916             break;
1917           if (h > 7)
1918             {
1919               if (base == 8)
1920                 break;
1921               else 
1922                 base = 10;
1923             }
1924           if (i == 2 && base == 10)
1925             break;
1926           x = x * 8 + h;
1927           d = d * 10 + h;
1928           p++;
1929         }
1930       if (base == 8 || i == 3)
1931         {
1932           data->type = REPL_TYPE_STRING;
1933           data->text = g_new0 (gchar, 8);
1934           g_unichar_to_utf8 (x, data->text);
1935         }
1936       else
1937         {
1938           data->type = REPL_TYPE_NUMERIC_REFERENCE;
1939           data->num = d;
1940         }
1941       break;
1942     case 0:
1943       error_detail = _("stray final '\\'");
1944       goto error;
1945       break;
1946     default:
1947       error_detail = _("unknown escape sequence");
1948       goto error;
1949     }
1950
1951   return p;
1952
1953  error:
1954   /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1955   tmp_error = g_error_new (G_REGEX_ERROR, 
1956                            G_REGEX_ERROR_REPLACE,
1957                            _("Error while parsing replacement "
1958                              "text \"%s\" at char %lu: %s"),
1959                            replacement, 
1960                            (gulong)(p - replacement),
1961                            error_detail);
1962   g_propagate_error (error, tmp_error);
1963
1964   return NULL;
1965 }
1966
1967 static GList *
1968 split_replacement (const gchar  *replacement,
1969                    GError      **error)
1970 {
1971   GList *list = NULL;
1972   InterpolationData *data;
1973   const gchar *p, *start;
1974   
1975   start = p = replacement; 
1976   while (*p)
1977     {
1978       if (*p == '\\')
1979         {
1980           data = g_new0 (InterpolationData, 1);
1981           start = p = expand_escape (replacement, p, data, error);
1982           if (p == NULL)
1983             {
1984               g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1985               g_list_free (list);
1986               free_interpolation_data (data);
1987
1988               return NULL;
1989             }
1990           list = g_list_prepend (list, data);
1991         }
1992       else
1993         {
1994           p++;
1995           if (*p == '\\' || *p == '\0')
1996             {
1997               if (p - start > 0)
1998                 {
1999                   data = g_new0 (InterpolationData, 1);
2000                   data->text = g_strndup (start, p - start);
2001                   data->type = REPL_TYPE_STRING;
2002                   list = g_list_prepend (list, data);
2003                 }
2004             }
2005         }
2006     }
2007
2008   return g_list_reverse (list);
2009 }
2010
2011 /* Change the case of c based on change_case. */
2012 #define CHANGE_CASE(c, change_case) \
2013         (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2014                 g_unichar_tolower (c) : \
2015                 g_unichar_toupper (c))
2016
2017 static void
2018 string_append (GString     *string,
2019                const gchar *text,
2020                ChangeCase  *change_case)
2021 {
2022   gunichar c;
2023
2024   if (text[0] == '\0')
2025     return;
2026
2027   if (*change_case == CHANGE_CASE_NONE)
2028     {
2029       g_string_append (string, text);
2030     }
2031   else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2032     {
2033       c = g_utf8_get_char (text);
2034       g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2035       g_string_append (string, g_utf8_next_char (text));
2036       *change_case = CHANGE_CASE_NONE;
2037     }
2038   else
2039     {
2040       while (*text != '\0')
2041         {
2042           c = g_utf8_get_char (text);
2043           g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2044           text = g_utf8_next_char (text);
2045         }
2046     }
2047 }
2048
2049 static gboolean
2050 interpolate_replacement (const GMatchInfo *match_info,
2051                          GString          *result,
2052                          gpointer          data)
2053 {
2054   GList *list;
2055   InterpolationData *idata;
2056   gchar *match;
2057   ChangeCase change_case = CHANGE_CASE_NONE;
2058
2059   for (list = data; list; list = list->next)
2060     {
2061       idata = list->data;
2062       switch (idata->type)
2063         {
2064         case REPL_TYPE_STRING:
2065           string_append (result, idata->text, &change_case);
2066           break;
2067         case REPL_TYPE_CHARACTER:
2068           g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2069           if (change_case & CHANGE_CASE_SINGLE_MASK)
2070             change_case = CHANGE_CASE_NONE;
2071           break;
2072         case REPL_TYPE_NUMERIC_REFERENCE:
2073           match = g_match_info_fetch (match_info, idata->num);
2074           if (match)
2075             {
2076               string_append (result, match, &change_case);
2077               g_free (match);
2078             }
2079           break;
2080         case REPL_TYPE_SYMBOLIC_REFERENCE:
2081           match = g_match_info_fetch_named (match_info, idata->text);
2082           if (match)
2083             {
2084               string_append (result, match, &change_case);
2085               g_free (match);
2086             }
2087           break;
2088         case REPL_TYPE_CHANGE_CASE:
2089           change_case = idata->change_case;
2090           break;
2091         }
2092     }
2093
2094   return FALSE; 
2095 }
2096
2097 /* whether actual match_info is needed for replacement, i.e.
2098  * whether there are references
2099  */
2100 static gboolean
2101 interpolation_list_needs_match (GList *list)
2102 {
2103   while (list != NULL)
2104     {
2105       InterpolationData *data = list->data;
2106
2107       if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2108           data->type == REPL_TYPE_NUMERIC_REFERENCE)
2109         {
2110           return TRUE;
2111         }
2112
2113       list = list->next;
2114     }
2115
2116   return FALSE;
2117 }
2118
2119 /**
2120  * g_regex_replace:
2121  * @regex: a #GRegex structure
2122  * @string: the string to perform matches against
2123  * @string_len: the length of @string, or -1 if @string is nul-terminated
2124  * @start_position: starting index of the string to match
2125  * @replacement: text to replace each match with
2126  * @match_options: options for the match
2127  * @error: location to store the error occuring, or %NULL to ignore errors
2128  *
2129  * Replaces all occurances of the pattern in @regex with the
2130  * replacement text. Backreferences of the form '\number' or 
2131  * '\g&lt;number&gt;' in the replacement text are interpolated by the 
2132  * number-th captured subexpression of the match, '\g&lt;name&gt;' refers 
2133  * to the captured subexpression with the given name. '\0' refers to the 
2134  * complete match, but '\0' followed by a number is the octal representation 
2135  * of a character. To include a literal '\' in the replacement, write '\\'.
2136  * There are also escapes that changes the case of the following text:
2137  *
2138  * <variablelist>
2139  * <varlistentry><term>\l</term>
2140  * <listitem>
2141  * <para>Convert to lower case the next character</para>
2142  * </listitem>
2143  * </varlistentry>
2144  * <varlistentry><term>\u</term>
2145  * <listitem>
2146  * <para>Convert to upper case the next character</para>
2147  * </listitem>
2148  * </varlistentry>
2149  * <varlistentry><term>\L</term>
2150  * <listitem>
2151  * <para>Convert to lower case till \E</para>
2152  * </listitem>
2153  * </varlistentry>
2154  * <varlistentry><term>\U</term>
2155  * <listitem>
2156  * <para>Convert to upper case till \E</para>
2157  * </listitem>
2158  * </varlistentry>
2159  * <varlistentry><term>\E</term>
2160  * <listitem>
2161  * <para>End case modification</para>
2162  * </listitem>
2163  * </varlistentry>
2164  * </variablelist>
2165  *
2166  * If you do not need to use backreferences use g_regex_replace_literal().
2167  *
2168  * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2169  * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2170  * you can use g_regex_replace_literal().
2171  *
2172  * Setting @start_position differs from just passing over a shortened 
2173  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that 
2174  * begins with any kind of lookbehind assertion, such as "\b".
2175  *
2176  * Returns: a newly allocated string containing the replacements
2177  *
2178  * Since: 2.14
2179  */
2180 gchar *
2181 g_regex_replace (const GRegex      *regex, 
2182                  const gchar       *string, 
2183                  gssize             string_len,
2184                  gint               start_position,
2185                  const gchar       *replacement,
2186                  GRegexMatchFlags   match_options,
2187                  GError           **error)
2188 {
2189   gchar *result;
2190   GList *list;
2191   GError *tmp_error = NULL;
2192
2193   g_return_val_if_fail (regex != NULL, NULL);
2194   g_return_val_if_fail (string != NULL, NULL);
2195   g_return_val_if_fail (start_position >= 0, NULL);
2196   g_return_val_if_fail (replacement != NULL, NULL);
2197   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2198   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2199
2200   list = split_replacement (replacement, &tmp_error);
2201   if (tmp_error != NULL)
2202     {
2203       g_propagate_error (error, tmp_error);
2204       return NULL;
2205     }
2206
2207   result = g_regex_replace_eval (regex, 
2208                                  string, string_len, start_position,
2209                                  match_options,
2210                                  interpolate_replacement,
2211                                  (gpointer)list,
2212                                  &tmp_error);
2213   if (tmp_error != NULL)
2214     g_propagate_error (error, tmp_error);
2215
2216   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2217   g_list_free (list);
2218
2219   return result;
2220 }
2221
2222 static gboolean
2223 literal_replacement (const GMatchInfo *match_info,
2224                      GString          *result,
2225                      gpointer          data)
2226 {
2227   g_string_append (result, data);
2228   return FALSE;
2229 }
2230
2231 /**
2232  * g_regex_replace_literal:
2233  * @regex: a #GRegex structure
2234  * @string: the string to perform matches against
2235  * @string_len: the length of @string, or -1 if @string is nul-terminated
2236  * @start_position: starting index of the string to match
2237  * @replacement: text to replace each match with
2238  * @match_options: options for the match
2239  * @error: location to store the error occuring, or %NULL to ignore errors
2240  *
2241  * Replaces all occurances of the pattern in @regex with the
2242  * replacement text. @replacement is replaced literally, to
2243  * include backreferences use g_regex_replace().
2244  *
2245  * Setting @start_position differs from just passing over a 
2246  * shortened string and setting #G_REGEX_MATCH_NOTBOL in the 
2247  * case of a pattern that begins with any kind of lookbehind 
2248  * assertion, such as "\b".
2249  *
2250  * Returns: a newly allocated string containing the replacements
2251  *
2252  * Since: 2.14
2253  */
2254 gchar *
2255 g_regex_replace_literal (const GRegex      *regex,
2256                          const gchar       *string,
2257                          gssize             string_len,
2258                          gint               start_position,
2259                          const gchar       *replacement,
2260                          GRegexMatchFlags   match_options,
2261                          GError           **error)
2262 {
2263   g_return_val_if_fail (replacement != NULL, NULL);
2264   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2265
2266   return g_regex_replace_eval (regex,
2267                                string, string_len, start_position,
2268                                match_options,
2269                                literal_replacement,
2270                                (gpointer)replacement,
2271                                error);
2272 }
2273
2274 /**
2275  * g_regex_replace_eval:
2276  * @regex: a #GRegex structure from g_regex_new()
2277  * @string: string to perform matches against
2278  * @string_len: the length of @string, or -1 if @string is nul-terminated
2279  * @start_position: starting index of the string to match
2280  * @match_options: options for the match
2281  * @eval: a function to call for each match
2282  * @user_data: user data to pass to the function
2283  * @error: location to store the error occuring, or %NULL to ignore errors
2284  *
2285  * Replaces occurances of the pattern in regex with the output of 
2286  * @eval for that occurance.
2287  *
2288  * Setting @start_position differs from just passing over a shortened 
2289  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
2290  * that begins with any kind of lookbehind assertion, such as "\b".
2291  *
2292  * Returns: a newly allocated string containing the replacements
2293  *
2294  * Since: 2.14
2295  */
2296 gchar *
2297 g_regex_replace_eval (const GRegex        *regex,
2298                       const gchar         *string,
2299                       gssize               string_len,
2300                       gint                 start_position,
2301                       GRegexMatchFlags     match_options,
2302                       GRegexEvalCallback   eval,
2303                       gpointer             user_data,
2304                       GError             **error)
2305 {
2306   GMatchInfo *match_info;
2307   GString *result;
2308   gint str_pos = 0;
2309   gboolean done = FALSE;
2310   GError *tmp_error = NULL;
2311
2312   g_return_val_if_fail (regex != NULL, NULL);
2313   g_return_val_if_fail (string != NULL, NULL);
2314   g_return_val_if_fail (start_position >= 0, NULL);
2315   g_return_val_if_fail (eval != NULL, NULL);
2316   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2317
2318   if (string_len < 0)
2319     string_len = strlen (string);
2320
2321   result = g_string_sized_new (string_len);
2322
2323   /* run down the string making matches. */
2324   g_regex_match_full (regex, string, string_len, start_position,
2325                       match_options, &match_info, &tmp_error);
2326   while (!done && g_match_info_matches (match_info))
2327     {
2328       g_string_append_len (result,
2329                            string + str_pos,
2330                            match_info->offsets[0] - str_pos);
2331       done = (*eval) (match_info, result, user_data);
2332       str_pos = match_info->offsets[1];
2333       g_match_info_next (match_info, &tmp_error);
2334     }
2335   g_match_info_free (match_info);
2336   if (tmp_error != NULL)
2337     {
2338       g_propagate_error (error, tmp_error);
2339       g_string_free (result, TRUE);
2340       return NULL;
2341     }
2342
2343   g_string_append_len (result, string + str_pos, string_len - str_pos);
2344   return g_string_free (result, FALSE);
2345 }
2346
2347 /**
2348  * g_regex_check_replacement:
2349  * @replacement: the replacement string
2350  * @has_references: location to store information about
2351  *   references in @replacement or %NULL
2352  * @error: location to store error
2353  *
2354  * Checks whether @replacement is a valid replacement string 
2355  * (see g_regex_replace()), i.e. that all escape sequences in 
2356  * it are valid.
2357  *
2358  * If @has_references is not %NULL then @replacement is checked 
2359  * for pattern references. For instance, replacement text 'foo\n'
2360  * does not contain references and may be evaluated without information
2361  * about actual match, but '\0\1' (whole match followed by first 
2362  * subpattern) requires valid #GMatchInfo object.
2363  *
2364  * Returns: whether @replacement is a valid replacement string
2365  *
2366  * Since: 2.14
2367  */
2368 gboolean
2369 g_regex_check_replacement (const gchar  *replacement,
2370                            gboolean     *has_references,
2371                            GError      **error)
2372 {
2373   GList *list;
2374   GError *tmp = NULL;
2375
2376   list = split_replacement (replacement, &tmp);
2377
2378   if (tmp)
2379   {
2380     g_propagate_error (error, tmp);
2381     return FALSE;
2382   }
2383
2384   if (has_references)
2385     *has_references = interpolation_list_needs_match (list);
2386
2387   g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2388   g_list_free (list);
2389
2390   return TRUE;
2391 }
2392
2393 /**
2394  * g_regex_escape_string:
2395  * @string: the string to escape
2396  * @length: the length of @string, or -1 if @string is nul-terminated
2397  *
2398  * Escapes the special characters used for regular expressions 
2399  * in @string, for instance "a.b*c" becomes "a\.b\*c". This 
2400  * function is useful to dynamically generate regular expressions.
2401  *
2402  * @string can contain nul characters that are replaced with "\0", 
2403  * in this case remember to specify the correct length of @string 
2404  * in @length.
2405  *
2406  * Returns: a newly-allocated escaped string
2407  *
2408  * Since: 2.14
2409  */
2410 gchar *
2411 g_regex_escape_string (const gchar *string,
2412                        gint         length)
2413 {
2414   GString *escaped;
2415   const char *p, *piece_start, *end;
2416
2417   g_return_val_if_fail (string != NULL, NULL);
2418
2419   if (length < 0)
2420     length = strlen (string);
2421
2422   end = string + length;
2423   p = piece_start = string;
2424   escaped = g_string_sized_new (length + 1);
2425
2426   while (p < end)
2427     {
2428       switch (*p)
2429         {
2430         case '\0':
2431         case '\\':
2432         case '|':
2433         case '(':
2434         case ')':
2435         case '[':
2436         case ']':
2437         case '{':
2438         case '}':
2439         case '^':
2440         case '$':
2441         case '*':
2442         case '+':
2443         case '?':
2444         case '.':
2445           if (p != piece_start)
2446             /* copy the previous piece. */
2447             g_string_append_len (escaped, piece_start, p - piece_start);
2448           g_string_append_c (escaped, '\\');
2449           if (*p == '\0')
2450             g_string_append_c (escaped, '0');
2451           else
2452             g_string_append_c (escaped, *p);
2453           piece_start = ++p;
2454           break;
2455         default:
2456           p = g_utf8_next_char (p);
2457           break;
2458         } 
2459   }
2460
2461   if (piece_start < end)
2462     g_string_append_len (escaped, piece_start, end - piece_start);
2463
2464   return g_string_free (escaped, FALSE);
2465 }
2466
2467 #define __G_REGEX_C__
2468 #include "galiasdef.c"