Documentation cleanups
[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   g_print ("compile opts: %x\n", compile_options);
926   if (compile_options & PCRE_UTF8)
927     g_print ("\tPCRE_UTF8\n");
928   if (compile_options & PCRE_NO_UTF8_CHECK)
929     g_print ("\tPCRE_NO_UTF8_CHECK\n");
930   if (compile_options & PCRE_NEWLINE_ANY)
931     g_print ("\tPCRE_NEWLINE_ANY\n");
932   /* compile the pattern */
933   re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
934
935   /* if the compilation failed, set the error member and return 
936    * immediately */
937   if (re == NULL)
938     {
939       GError *tmp_error = g_error_new (G_REGEX_ERROR, 
940                                        G_REGEX_ERROR_COMPILE,
941                                        _("Error while compiling regular "
942                                          "expression %s at char %d: %s"),
943                                        pattern, erroffset, errmsg);
944       g_propagate_error (error, tmp_error);
945
946       return NULL;
947     }
948
949   regex = g_new0 (GRegex, 1);
950   regex->ref_count = 1;
951   regex->pattern = g_strdup (pattern);
952   regex->pcre_re = re;
953   regex->compile_opts = compile_options;
954   regex->match_opts = match_options;
955
956   if (optimize)
957     {
958       regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
959       if (errmsg != NULL)
960         {
961           GError *tmp_error = g_error_new (G_REGEX_ERROR,
962                                            G_REGEX_ERROR_OPTIMIZE, 
963                                            _("Error while optimizing "
964                                              "regular expression %s: %s"),
965                                            regex->pattern,
966                                            errmsg);
967           g_propagate_error (error, tmp_error);
968           return NULL;
969         }
970     }
971
972   return regex;
973 }
974
975 /**
976  * g_regex_get_pattern:
977  * @regex: a #GRegex structure
978  *
979  * Gets the pattern string associated with @regex, i.e. a copy of 
980  * the string passed to g_regex_new().
981  *
982  * Returns: the pattern of @regex
983  *
984  * Since: 2.14
985  */
986 const gchar *
987 g_regex_get_pattern (const GRegex *regex)
988 {
989   g_return_val_if_fail (regex != NULL, NULL);
990
991   return regex->pattern;
992 }
993
994 /**
995  * g_regex_get_max_backref:
996  * @regex: a #GRegex
997  *  
998  * Returns the number of the highest back reference
999  * in the pattern, or 0 if the pattern does not contain
1000  * back references.
1001  *
1002  * Returns: the number of the highest back reference
1003  *
1004  * Since: 2.14
1005  */
1006 gint
1007 g_regex_get_max_backref (const GRegex *regex)
1008 {
1009   gint value;
1010
1011   pcre_fullinfo (regex->pcre_re, regex->extra,
1012                  PCRE_INFO_BACKREFMAX, &value);
1013
1014   return value;
1015 }
1016
1017 /**
1018  * g_regex_get_capture_count:
1019  * @regex: a #GRegex
1020  *
1021  * Returns the number of capturing subpatterns in the pattern.
1022  *
1023  * Returns: the number of capturing subpatterns
1024  *
1025  * Since: 2.14
1026  */
1027 gint
1028 g_regex_get_capture_count (const GRegex *regex)
1029 {
1030   gint value;
1031
1032   pcre_fullinfo (regex->pcre_re, regex->extra,
1033                  PCRE_INFO_CAPTURECOUNT, &value);
1034
1035   return value;
1036 }
1037
1038 /**
1039  * g_regex_match_simple:
1040  * @pattern: the regular expression
1041  * @string: the string to scan for matches
1042  * @compile_options: compile options for the regular expression
1043  * @match_options: match options
1044  *
1045  * Scans for a match in @string for @pattern.
1046  *
1047  * This function is equivalent to g_regex_match() but it does not
1048  * require to compile the pattern with g_regex_new(), avoiding some
1049  * lines of code when you need just to do a match without extracting
1050  * substrings, capture counts, and so on.
1051  *
1052  * If this function is to be called on the same @pattern more than
1053  * once, it's more efficient to compile the pattern once with
1054  * g_regex_new() and then use g_regex_match().
1055  *
1056  * Returns: %TRUE is the string matched, %FALSE otherwise
1057  *
1058  * Since: 2.14
1059  */
1060 gboolean
1061 g_regex_match_simple (const gchar        *pattern, 
1062                       const gchar        *string, 
1063                       GRegexCompileFlags  compile_options,
1064                       GRegexMatchFlags    match_options)
1065 {
1066   GRegex *regex;
1067   gboolean result;
1068
1069   regex = g_regex_new (pattern, compile_options, 0, NULL);
1070   if (!regex)
1071     return FALSE;
1072   result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1073   g_regex_unref (regex);
1074   return result;
1075 }
1076
1077 /**
1078  * g_regex_match:
1079  * @regex: a #GRegex structure from g_regex_new()
1080  * @string: the string to scan for matches
1081  * @match_options: match options
1082  * @match_info: pointer to location where to store the #GMatchInfo, 
1083  *   or %NULL if you do not need it
1084  *
1085  * Scans for a match in string for the pattern in @regex. 
1086  * The @match_options are combined with the match options specified 
1087  * when the @regex structure was created, letting you have more 
1088  * flexibility in reusing #GRegex structures.
1089  *
1090  * A #GMatchInfo structure, used to get information on the match, 
1091  * is stored in @match_info if not %NULL. Note that if @match_info 
1092  * is not %NULL then it is created even if the function returns %FALSE, 
1093  * i.e. you must free it regardless if regular expression actually matched.
1094  *
1095  * To retrieve all the non-overlapping matches of the pattern in 
1096  * string you can use g_match_info_next().
1097  *
1098  * <informalexample><programlisting>
1099  * static void
1100  * print_uppercase_words (const gchar *string)
1101  * {
1102  *   /&ast; Print all uppercase-only words. &ast;/
1103  *   GRegex *regex;
1104  *   GMatchInfo *match_info;
1105  *   &nbsp;
1106  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1107  *   g_regex_match (regex, string, 0, &amp;match_info);
1108  *   while (g_match_info_matches (match_info))
1109  *     {
1110  *       gchar *word = g_match_info_fetch (match_info, 0);
1111  *       g_print ("Found: %s\n", word);
1112  *       g_free (word);
1113  *       g_match_info_next (match_info, NULL);
1114  *     }
1115  *   g_match_info_free (match_info);
1116  *   g_regex_unref (regex);
1117  * }
1118  * </programlisting></informalexample>
1119  *
1120  * Returns: %TRUE is the string matched, %FALSE otherwise
1121  *
1122  * Since: 2.14
1123  */
1124 gboolean
1125 g_regex_match (const GRegex      *regex, 
1126                const gchar       *string, 
1127                GRegexMatchFlags   match_options,
1128                GMatchInfo       **match_info)
1129 {
1130   return g_regex_match_full (regex, string, -1, 0, match_options,
1131                              match_info, NULL);
1132 }
1133
1134 /**
1135  * g_regex_match_full:
1136  * @regex: a #GRegex structure from g_regex_new()
1137  * @string: the string to scan for matches
1138  * @string_len: the length of @string, or -1 if @string is nul-terminated
1139  * @start_position: starting index of the string to match
1140  * @match_options: match options
1141  * @match_info: pointer to location where to store the #GMatchInfo, 
1142  *   or %NULL if you do not need it
1143  * @error: location to store the error occuring, or %NULL to ignore errors
1144  *
1145  * Scans for a match in string for the pattern in @regex. 
1146  * The @match_options are combined with the match options specified 
1147  * when the @regex structure was created, letting you have more 
1148  * flexibility in reusing #GRegex structures.
1149  *
1150  * Setting @start_position differs from just passing over a shortened 
1151  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1152  * that begins with any kind of lookbehind assertion, such as "\b".
1153  *
1154  * A #GMatchInfo structure, used to get information on the match, is 
1155  * stored in @match_info if not %NULL. Note that if @match_info is 
1156  * not %NULL then it is created even if the function returns %FALSE, 
1157  * i.e. you must free it regardless if regular expression actually 
1158  * matched.
1159  *
1160  * @string is not copied and is used in #GMatchInfo internally. If 
1161  * you use any #GMatchInfo method (except g_match_info_free()) after 
1162  * freeing or modifying @string then the behaviour is undefined.
1163  *
1164  * To retrieve all the non-overlapping matches of the pattern in 
1165  * string you can use g_match_info_next().
1166  *
1167  * <informalexample><programlisting>
1168  * static void
1169  * print_uppercase_words (const gchar *string)
1170  * {
1171  *   /&ast; Print all uppercase-only words. &ast;/
1172  *   GRegex *regex;
1173  *   GMatchInfo *match_info;
1174  *   GError *error = NULL;
1175  *   &nbsp;
1176  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1177  *   g_regex_match_full (regex, string, -1, 0, 0, &amp;match_info, &amp;error);
1178  *   while (g_match_info_matches (match_info))
1179  *     {
1180  *       gchar *word = g_match_info_fetch (match_info, 0);
1181  *       g_print ("Found: %s\n", word);
1182  *       g_free (word);
1183  *       g_match_info_next (match_info, &amp;error);
1184  *     }
1185  *   g_match_info_free (match_info);
1186  *   g_regex_unref (regex);
1187  *   if (error != NULL)
1188  *     {
1189  *       g_printerr ("Error while matching: %s\n", error->message);
1190  *       g_error_free (error);
1191  *     }
1192  * }
1193  * </programlisting></informalexample>
1194  *
1195  * Returns: %TRUE is the string matched, %FALSE otherwise
1196  *
1197  * Since: 2.14
1198  */
1199 gboolean
1200 g_regex_match_full (const GRegex      *regex,
1201                     const gchar       *string,
1202                     gssize             string_len,
1203                     gint               start_position,
1204                     GRegexMatchFlags   match_options,
1205                     GMatchInfo       **match_info,
1206                     GError           **error)
1207 {
1208   GMatchInfo *info;
1209   gboolean match_ok;
1210
1211   g_return_val_if_fail (regex != NULL, FALSE);
1212   g_return_val_if_fail (string != NULL, FALSE);
1213   g_return_val_if_fail (start_position >= 0, FALSE);
1214   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1215   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1216
1217   info = match_info_new (regex, string, string_len, start_position,
1218                          match_options, FALSE);
1219   match_ok = g_match_info_next (info, error);
1220   if (match_info != NULL)
1221     *match_info = info;
1222   else
1223     g_match_info_free (info);
1224
1225   return match_ok;
1226 }
1227
1228 /**
1229  * g_regex_match_all:
1230  * @regex: a #GRegex structure from g_regex_new()
1231  * @string: the string to scan for matches
1232  * @match_options: match options
1233  * @match_info: pointer to location where to store the #GMatchInfo, 
1234  *   or %NULL if you do not need it
1235  *
1236  * Using the standard algorithm for regular expression matching only 
1237  * the longest match in the string is retrieved. This function uses 
1238  * a different algorithm so it can retrieve all the possible matches.
1239  * For more documentation see g_regex_match_all_full().
1240  *
1241  * A #GMatchInfo structure, used to get information on the match, is 
1242  * stored in @match_info if not %NULL. Note that if @match_info is 
1243  * not %NULL then it is created even if the function returns %FALSE, 
1244  * i.e. you must free it regardless if regular expression actually 
1245  * matched.
1246  *
1247  * Returns: %TRUE is the string matched, %FALSE otherwise
1248  *
1249  * Since: 2.14
1250  */
1251 gboolean
1252 g_regex_match_all (const GRegex      *regex,
1253                    const gchar       *string,
1254                    GRegexMatchFlags   match_options,
1255                    GMatchInfo       **match_info)
1256 {
1257   return g_regex_match_all_full (regex, string, -1, 0, match_options,
1258                                  match_info, NULL);
1259 }
1260
1261 /**
1262  * g_regex_match_all_full:
1263  * @regex: a #GRegex structure from g_regex_new()
1264  * @string: the string to scan for matches
1265  * @string_len: the length of @string, or -1 if @string is nul-terminated
1266  * @start_position: starting index of the string to match
1267  * @match_options: match options
1268  * @match_info: pointer to location where to store the #GMatchInfo, 
1269  *   or %NULL if you do not need it
1270  * @error: location to store the error occuring, or %NULL to ignore errors
1271  *
1272  * Using the standard algorithm for regular expression matching only 
1273  * the longest match in the string is retrieved, it is not possibile 
1274  * to obtain all the available matches. For instance matching
1275  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;" 
1276  * you get "&lt;a&gt; &lt;b&gt; &lt;c&gt;".
1277  *
1278  * This function uses a different algorithm (called DFA, i.e. deterministic
1279  * finite automaton), so it can retrieve all the possible matches, all
1280  * starting at the same point in the string. For instance matching
1281  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;" 
1282  * you would obtain three matches: "&lt;a&gt; &lt;b&gt; &lt;c&gt;",
1283  * "&lt;a&gt; &lt;b&gt;" and "&lt;a&gt;".
1284  *
1285  * The number of matched strings is retrieved using
1286  * g_match_info_get_match_count(). To obtain the matched strings and 
1287  * their position you can use, respectively, g_match_info_fetch() and 
1288  * g_match_info_fetch_pos(). Note that the strings are returned in 
1289  * reverse order of length; that is, the longest matching string is 
1290  * given first.
1291  *
1292  * Note that the DFA algorithm is slower than the standard one and it 
1293  * is not able to capture substrings, so backreferences do not work.
1294  *
1295  * Setting @start_position differs from just passing over a shortened 
1296  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1297  * that begins with any kind of lookbehind assertion, such as "\b".
1298  *
1299  * A #GMatchInfo structure, used to get information on the match, is 
1300  * stored in @match_info if not %NULL. Note that if @match_info is 
1301  * not %NULL then it is created even if the function returns %FALSE, 
1302  * i.e. you must free it regardless if regular expression actually 
1303  * matched.
1304  *
1305  * Returns: %TRUE is the string matched, %FALSE otherwise
1306  *
1307  * Since: 2.14
1308  */
1309 gboolean
1310 g_regex_match_all_full (const GRegex      *regex,
1311                         const gchar       *string,
1312                         gssize             string_len,
1313                         gint               start_position,
1314                         GRegexMatchFlags   match_options,
1315                         GMatchInfo       **match_info,
1316                         GError           **error)
1317 {
1318   GMatchInfo *info;
1319   gboolean done;
1320
1321   g_return_val_if_fail (regex != NULL, FALSE);
1322   g_return_val_if_fail (string != NULL, FALSE);
1323   g_return_val_if_fail (start_position >= 0, FALSE);
1324   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1326
1327   info = match_info_new (regex, string, string_len, start_position,
1328                          match_options, TRUE);
1329
1330   done = FALSE;
1331   while (!done)
1332     {
1333       done = TRUE;
1334       info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1335                                      info->string, info->string_len,
1336                                      info->pos,
1337                                      regex->match_opts | match_options,
1338                                      info->offsets, info->n_offsets,
1339                                      info->workspace, info->n_workspace);
1340       if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1341         {
1342           /* info->workspace is too small. */
1343           info->n_workspace *= 2;
1344           info->workspace = g_realloc (info->workspace,
1345                                        info->n_workspace * sizeof (gint));
1346           done = FALSE;
1347         }
1348       else if (info->matches == 0)
1349         {
1350           /* info->offsets is too small. */
1351           info->n_offsets *= 2;
1352           info->offsets = g_realloc (info->offsets,
1353                                      info->n_offsets * sizeof (gint));
1354           done = FALSE;
1355         }
1356       else if (IS_PCRE_ERROR (info->matches))
1357         {
1358           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1359                        _("Error while matching regular expression %s: %s"),
1360                        regex->pattern, match_error (info->matches));
1361         }
1362     }
1363
1364   /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1365   info->pos = -1;
1366
1367   if (match_info != NULL)
1368     *match_info = info;
1369   else
1370     g_match_info_free (info);
1371
1372   return info->matches >= 0;
1373 }
1374
1375 /**
1376  * g_regex_get_string_number:
1377  * @regex: #GRegex structure
1378  * @name: name of the subexpression
1379  *
1380  * Retrieves the number of the subexpression named @name.
1381  *
1382  * Returns: The number of the subexpression or -1 if @name 
1383  *   does not exists
1384  *
1385  * Since: 2.14
1386  */
1387 gint
1388 g_regex_get_string_number (const GRegex *regex,
1389                            const gchar  *name)
1390 {
1391   gint num;
1392
1393   g_return_val_if_fail (regex != NULL, -1);
1394   g_return_val_if_fail (name != NULL, -1);
1395
1396   num = pcre_get_stringnumber (regex->pcre_re, name);
1397   if (num == PCRE_ERROR_NOSUBSTRING)
1398     num = -1;
1399
1400   return num;
1401 }
1402
1403 /**
1404  * g_regex_split_simple:
1405  * @pattern: the regular expression
1406  * @string: the string to scan for matches
1407  * @compile_options: compile options for the regular expression
1408  * @match_options: match options
1409  *
1410  * Breaks the string on the pattern, and returns an array of 
1411  * the tokens. If the pattern contains capturing parentheses, 
1412  * then the text for each of the substrings will also be returned. 
1413  * If the pattern does not match anywhere in the string, then the 
1414  * whole string is returned as the first token.
1415  *
1416  * This function is equivalent to g_regex_split() but it does 
1417  * not require to compile the pattern with g_regex_new(), avoiding 
1418  * some lines of code when you need just to do a split without 
1419  * extracting substrings, capture counts, and so on.
1420  *
1421  * If this function is to be called on the same @pattern more than
1422  * once, it's more efficient to compile the pattern once with
1423  * g_regex_new() and then use g_regex_split().
1424  *
1425  * As a special case, the result of splitting the empty string "" 
1426  * is an empty vector, not a vector containing a single string. 
1427  * The reason for this special case is that being able to represent 
1428  * a empty vector is typically more useful than consistent handling 
1429  * of empty elements. If you do need to represent empty elements, 
1430  * you'll need to check for the empty string before calling this 
1431  * function.
1432  *
1433  * A pattern that can match empty strings splits @string into 
1434  * separate characters wherever it matches the empty string between 
1435  * characters. For example splitting "ab c" using as a separator 
1436  * "\s*", you will get "a", "b" and "c".
1437  *
1438  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1439  *
1440  * Since: 2.14
1441  **/
1442 gchar **
1443 g_regex_split_simple (const gchar        *pattern,
1444                       const gchar        *string, 
1445                       GRegexCompileFlags  compile_options,
1446                       GRegexMatchFlags    match_options)
1447 {
1448   GRegex *regex;
1449   gchar **result;
1450
1451   regex = g_regex_new (pattern, compile_options, 0, NULL);
1452   if (!regex)
1453     return NULL;
1454   result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1455   g_regex_unref (regex);
1456   return result;
1457 }
1458
1459 /**
1460  * g_regex_split:
1461  * @regex: a #GRegex structure
1462  * @string: the string to split with the pattern
1463  * @match_options: match time option flags
1464  *
1465  * Breaks the string on the pattern, and returns an array of the tokens.
1466  * If the pattern contains capturing parentheses, then the text for each
1467  * of the substrings will also be returned. If the pattern does not match
1468  * anywhere in the string, then the whole string is returned as the first
1469  * token.
1470  *
1471  * As a special case, the result of splitting the empty string "" is an
1472  * empty vector, not a vector containing a single string. The reason for
1473  * this special case is that being able to represent a empty vector is
1474  * typically more useful than consistent handling of empty elements. If
1475  * you do need to represent empty elements, you'll need to check for the
1476  * empty string before calling this function.
1477  *
1478  * A pattern that can match empty strings splits @string into separate
1479  * characters wherever it matches the empty string between characters.
1480  * For example splitting "ab c" using as a separator "\s*", you will get
1481  * "a", "b" and "c".
1482  *
1483  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1484  *
1485  * Since: 2.14
1486  **/
1487 gchar **
1488 g_regex_split (const GRegex     *regex, 
1489                const gchar      *string, 
1490                GRegexMatchFlags  match_options)
1491 {
1492   return g_regex_split_full (regex, string, -1, 0,
1493                              match_options, 0, NULL);
1494 }
1495
1496 /**
1497  * g_regex_split_full:
1498  * @regex: a #GRegex structure
1499  * @string: the string to split with the pattern
1500  * @string_len: the length of @string, or -1 if @string is nul-terminated
1501  * @start_position: starting index of the string to match
1502  * @match_options: match time option flags
1503  * @max_tokens: the maximum number of tokens to split @string into. 
1504  *   If this is less than 1, the string is split completely
1505  * @error: return location for a #GError
1506  *
1507  * Breaks the string on the pattern, and returns an array of the tokens.
1508  * If the pattern contains capturing parentheses, then the text for each
1509  * of the substrings will also be returned. If the pattern does not match
1510  * anywhere in the string, then the whole string is returned as the first
1511  * token.
1512  *
1513  * As a special case, the result of splitting the empty string "" is an
1514  * empty vector, not a vector containing a single string. The reason for
1515  * this special case is that being able to represent a empty vector is
1516  * typically more useful than consistent handling of empty elements. If
1517  * you do need to represent empty elements, you'll need to check for the
1518  * empty string before calling this function.
1519  *
1520  * A pattern that can match empty strings splits @string into separate
1521  * characters wherever it matches the empty string between characters.
1522  * For example splitting "ab c" using as a separator "\s*", you will get
1523  * "a", "b" and "c".
1524  *
1525  * Setting @start_position differs from just passing over a shortened 
1526  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1527  * that begins with any kind of lookbehind assertion, such as "\b".
1528  *
1529  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1530  *
1531  * Since: 2.14
1532  **/
1533 gchar **
1534 g_regex_split_full (const GRegex      *regex, 
1535                     const gchar       *string, 
1536                     gssize             string_len,
1537                     gint               start_position,
1538                     GRegexMatchFlags   match_options,
1539                     gint               max_tokens,
1540                     GError           **error)
1541 {
1542   GError *tmp_error = NULL;
1543   GMatchInfo *match_info;
1544   GList *list, *last;
1545   gint i;
1546   gint token_count;
1547   gboolean match_ok;
1548   /* position of the last separator. */
1549   gint last_separator_end;
1550   /* was the last match 0 bytes long? */
1551   gboolean last_match_is_empty;
1552   /* the returned array of char **s */
1553   gchar **string_list;
1554
1555   g_return_val_if_fail (regex != NULL, NULL);
1556   g_return_val_if_fail (string != NULL, NULL);
1557   g_return_val_if_fail (start_position >= 0, NULL);
1558   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1559   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1560
1561   if (max_tokens <= 0)
1562     max_tokens = G_MAXINT;
1563
1564   if (string_len < 0)
1565     string_len = strlen (string);
1566
1567   /* zero-length string */
1568   if (string_len - start_position == 0)
1569     return g_new0 (gchar *, 1);
1570
1571   if (max_tokens == 1)
1572     {
1573       string_list = g_new0 (gchar *, 2);
1574       string_list[0] = g_strndup (&string[start_position],
1575                                   string_len - start_position);
1576       return string_list;
1577     }
1578
1579   list = NULL;
1580   token_count = 0;
1581   last_separator_end = start_position;
1582   last_match_is_empty = FALSE;
1583
1584   match_ok = g_regex_match_full (regex, string, string_len, start_position,
1585                                  match_options, &match_info, &tmp_error);
1586   while (tmp_error == NULL)
1587     {
1588       if (match_ok)
1589         {
1590           last_match_is_empty =
1591                     (match_info->offsets[0] == match_info->offsets[1]);
1592
1593           /* we need to skip empty separators at the same position of the end
1594            * of another separator. e.g. the string is "a b" and the separator
1595            * is " *", so from 1 to 2 we have a match and at position 2 we have
1596            * an empty match. */
1597           if (last_separator_end != match_info->offsets[1])
1598             {
1599               gchar *token;
1600               gint match_count;
1601
1602               token = g_strndup (string + last_separator_end,
1603                                  match_info->offsets[0] - last_separator_end);
1604               list = g_list_prepend (list, token);
1605               token_count++;
1606
1607               /* if there were substrings, these need to be added to
1608                * the list. */
1609               match_count = g_match_info_get_match_count (match_info);
1610               if (match_count > 1)
1611                 {
1612                   for (i = 1; i < match_count; i++)
1613                     list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1614                 }
1615             }
1616         }
1617       else
1618         {
1619           /* if there was no match, copy to end of string. */
1620           if (!last_match_is_empty)
1621             {
1622               gchar *token = g_strndup (string + last_separator_end,
1623                                         match_info->string_len - last_separator_end);
1624               list = g_list_prepend (list, token);
1625             }
1626           /* no more tokens, end the loop. */
1627           break;
1628         }
1629
1630       /* -1 to leave room for the last part. */
1631       if (token_count >= max_tokens - 1)
1632         {
1633           /* we have reached the maximum number of tokens, so we copy
1634            * the remaining part of the string. */
1635           if (last_match_is_empty)
1636             {
1637               /* the last match was empty, so we have moved one char
1638                * after the real position to avoid empty matches at the
1639                * same position. */
1640               match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1641             }
1642           /* the if is needed in the case we have terminated the available
1643            * tokens, but we are at the end of the string, so there are no
1644            * characters left to copy. */
1645           if (string_len > match_info->pos)
1646             {
1647               gchar *token = g_strndup (string + match_info->pos,
1648                                         string_len - match_info->pos);
1649               list = g_list_prepend (list, token);
1650             }
1651           /* end the loop. */
1652           break;
1653         }
1654
1655       last_separator_end = match_info->pos;
1656       if (last_match_is_empty)
1657         /* if the last match was empty, g_match_info_next() has moved
1658          * forward to avoid infinite loops, but we still need to copy that
1659          * character. */
1660         last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1661
1662       match_ok = g_match_info_next (match_info, &tmp_error);
1663     }
1664   g_match_info_free (match_info);
1665   if (tmp_error != NULL)
1666     {
1667       g_propagate_error (error, tmp_error);
1668       g_list_foreach (list, (GFunc)g_free, NULL);
1669       g_list_free (list);
1670       match_info->pos = -1;
1671       return NULL;
1672     }
1673
1674   string_list = g_new (gchar *, g_list_length (list) + 1);
1675   i = 0;
1676   for (last = g_list_last (list); last; last = g_list_previous (last))
1677     string_list[i++] = last->data;
1678   string_list[i] = 0;
1679   g_list_free (list);
1680
1681   return string_list;
1682 }
1683
1684 enum
1685 {
1686   REPL_TYPE_STRING,
1687   REPL_TYPE_CHARACTER,
1688   REPL_TYPE_SYMBOLIC_REFERENCE,
1689   REPL_TYPE_NUMERIC_REFERENCE,
1690   REPL_TYPE_CHANGE_CASE
1691 }; 
1692
1693 typedef enum
1694 {
1695   CHANGE_CASE_NONE         = 1 << 0,
1696   CHANGE_CASE_UPPER        = 1 << 1,
1697   CHANGE_CASE_LOWER        = 1 << 2,
1698   CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1699   CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1700   CHANGE_CASE_SINGLE_MASK  = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1701   CHANGE_CASE_LOWER_MASK   = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1702   CHANGE_CASE_UPPER_MASK   = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1703 } ChangeCase;
1704
1705 struct _InterpolationData
1706 {
1707   gchar     *text;   
1708   gint       type;   
1709   gint       num;
1710   gchar      c;
1711   ChangeCase change_case;
1712 };
1713
1714 static void
1715 free_interpolation_data (InterpolationData *data)
1716 {
1717   g_free (data->text);
1718   g_free (data);
1719 }
1720
1721 static const gchar *
1722 expand_escape (const gchar        *replacement,
1723                const gchar        *p, 
1724                InterpolationData  *data,
1725                GError            **error)
1726 {
1727   const gchar *q, *r;
1728   gint x, d, h, i;
1729   const gchar *error_detail;
1730   gint base = 0;
1731   GError *tmp_error = NULL;
1732
1733   p++;
1734   switch (*p)
1735     {
1736     case 't':
1737       p++;
1738       data->c = '\t';
1739       data->type = REPL_TYPE_CHARACTER;
1740       break;
1741     case 'n':
1742       p++;
1743       data->c = '\n';
1744       data->type = REPL_TYPE_CHARACTER;
1745       break;
1746     case 'v':
1747       p++;
1748       data->c = '\v';
1749       data->type = REPL_TYPE_CHARACTER;
1750       break;
1751     case 'r':
1752       p++;
1753       data->c = '\r';
1754       data->type = REPL_TYPE_CHARACTER;
1755       break;
1756     case 'f':
1757       p++;
1758       data->c = '\f';
1759       data->type = REPL_TYPE_CHARACTER;
1760       break;
1761     case 'a':
1762       p++;
1763       data->c = '\a';
1764       data->type = REPL_TYPE_CHARACTER;
1765       break;
1766     case 'b':
1767       p++;
1768       data->c = '\b';
1769       data->type = REPL_TYPE_CHARACTER;
1770       break;
1771     case '\\':
1772       p++;
1773       data->c = '\\';
1774       data->type = REPL_TYPE_CHARACTER;
1775       break;
1776     case 'x':
1777       p++;
1778       x = 0;
1779       if (*p == '{')
1780         {
1781           p++;
1782           do 
1783             {
1784               h = g_ascii_xdigit_value (*p);
1785               if (h < 0)
1786                 {
1787                   error_detail = _("hexadecimal digit or '}' expected");
1788                   goto error;
1789                 }
1790               x = x * 16 + h;
1791               p++;
1792             }
1793           while (*p != '}');
1794           p++;
1795         }
1796       else
1797         {
1798           for (i = 0; i < 2; i++)
1799             {
1800               h = g_ascii_xdigit_value (*p);
1801               if (h < 0)
1802                 {
1803                   error_detail = _("hexadecimal digit expected");
1804                   goto error;
1805                 }
1806               x = x * 16 + h;
1807               p++;
1808             }
1809         }
1810       data->type = REPL_TYPE_STRING;
1811       data->text = g_new0 (gchar, 8);
1812       g_unichar_to_utf8 (x, data->text);
1813       break;
1814     case 'l':
1815       p++;
1816       data->type = REPL_TYPE_CHANGE_CASE;
1817       data->change_case = CHANGE_CASE_LOWER_SINGLE;
1818       break;
1819     case 'u':
1820       p++;
1821       data->type = REPL_TYPE_CHANGE_CASE;
1822       data->change_case = CHANGE_CASE_UPPER_SINGLE;
1823       break;
1824     case 'L':
1825       p++;
1826       data->type = REPL_TYPE_CHANGE_CASE;
1827       data->change_case = CHANGE_CASE_LOWER;
1828       break;
1829     case 'U':
1830       p++;
1831       data->type = REPL_TYPE_CHANGE_CASE;
1832       data->change_case = CHANGE_CASE_UPPER;
1833       break;
1834     case 'E':
1835       p++;
1836       data->type = REPL_TYPE_CHANGE_CASE;
1837       data->change_case = CHANGE_CASE_NONE;
1838       break;
1839     case 'g':
1840       p++;
1841       if (*p != '<')
1842         {
1843           error_detail = _("missing '<' in symbolic reference");
1844           goto error;
1845         }
1846       q = p + 1;
1847       do 
1848         {
1849           p++;
1850           if (!*p)
1851             {
1852               error_detail = _("unfinished symbolic reference");
1853               goto error;
1854             }
1855         }
1856       while (*p != '>');
1857       if (p - q == 0)
1858         {
1859           error_detail = _("zero-length symbolic reference");
1860           goto error;
1861         }
1862       if (g_ascii_isdigit (*q))
1863         {
1864           x = 0;
1865           do 
1866             {
1867               h = g_ascii_digit_value (*q);
1868               if (h < 0)
1869                 {
1870                   error_detail = _("digit expected");
1871                   p = q;
1872                   goto error;
1873                 }
1874               x = x * 10 + h;
1875               q++;
1876             }
1877           while (q != p);
1878           data->num = x;
1879           data->type = REPL_TYPE_NUMERIC_REFERENCE;
1880         }
1881       else
1882         {
1883           r = q;
1884           do 
1885             {
1886               if (!g_ascii_isalnum (*r))
1887                 {
1888                   error_detail = _("illegal symbolic reference");
1889                   p = r;
1890                   goto error;
1891                 }
1892               r++;
1893             }
1894           while (r != p);
1895           data->text = g_strndup (q, p - q);
1896           data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1897         }
1898       p++;
1899       break;
1900     case '0':
1901       /* if \0 is followed by a number is an octal number representing a
1902        * character, else it is a numeric reference. */
1903       if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1904         {
1905           base = 8;
1906           p = g_utf8_next_char (p);
1907         }
1908     case '1':
1909     case '2':
1910     case '3':
1911     case '4':
1912     case '5':
1913     case '6':
1914     case '7':
1915     case '8':
1916     case '9':
1917       x = 0;
1918       d = 0;
1919       for (i = 0; i < 3; i++)
1920         {
1921           h = g_ascii_digit_value (*p);
1922           if (h < 0) 
1923             break;
1924           if (h > 7)
1925             {
1926               if (base == 8)
1927                 break;
1928               else 
1929                 base = 10;
1930             }
1931           if (i == 2 && base == 10)
1932             break;
1933           x = x * 8 + h;
1934           d = d * 10 + h;
1935           p++;
1936         }
1937       if (base == 8 || i == 3)
1938         {
1939           data->type = REPL_TYPE_STRING;
1940           data->text = g_new0 (gchar, 8);
1941           g_unichar_to_utf8 (x, data->text);
1942         }
1943       else
1944         {
1945           data->type = REPL_TYPE_NUMERIC_REFERENCE;
1946           data->num = d;
1947         }
1948       break;
1949     case 0:
1950       error_detail = _("stray final '\\'");
1951       goto error;
1952       break;
1953     default:
1954       error_detail = _("unknown escape sequence");
1955       goto error;
1956     }
1957
1958   return p;
1959
1960  error:
1961   /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1962   tmp_error = g_error_new (G_REGEX_ERROR, 
1963                            G_REGEX_ERROR_REPLACE,
1964                            _("Error while parsing replacement "
1965                              "text \"%s\" at char %lu: %s"),
1966                            replacement, 
1967                            (gulong)(p - replacement),
1968                            error_detail);
1969   g_propagate_error (error, tmp_error);
1970
1971   return NULL;
1972 }
1973
1974 static GList *
1975 split_replacement (const gchar  *replacement,
1976                    GError      **error)
1977 {
1978   GList *list = NULL;
1979   InterpolationData *data;
1980   const gchar *p, *start;
1981   
1982   start = p = replacement; 
1983   while (*p)
1984     {
1985       if (*p == '\\')
1986         {
1987           data = g_new0 (InterpolationData, 1);
1988           start = p = expand_escape (replacement, p, data, error);
1989           if (p == NULL)
1990             {
1991               g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1992               g_list_free (list);
1993               free_interpolation_data (data);
1994
1995               return NULL;
1996             }
1997           list = g_list_prepend (list, data);
1998         }
1999       else
2000         {
2001           p++;
2002           if (*p == '\\' || *p == '\0')
2003             {
2004               if (p - start > 0)
2005                 {
2006                   data = g_new0 (InterpolationData, 1);
2007                   data->text = g_strndup (start, p - start);
2008                   data->type = REPL_TYPE_STRING;
2009                   list = g_list_prepend (list, data);
2010                 }
2011             }
2012         }
2013     }
2014
2015   return g_list_reverse (list);
2016 }
2017
2018 /* Change the case of c based on change_case. */
2019 #define CHANGE_CASE(c, change_case) \
2020         (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2021                 g_unichar_tolower (c) : \
2022                 g_unichar_toupper (c))
2023
2024 static void
2025 string_append (GString     *string,
2026                const gchar *text,
2027                ChangeCase  *change_case)
2028 {
2029   gunichar c;
2030
2031   if (text[0] == '\0')
2032     return;
2033
2034   if (*change_case == CHANGE_CASE_NONE)
2035     {
2036       g_string_append (string, text);
2037     }
2038   else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2039     {
2040       c = g_utf8_get_char (text);
2041       g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2042       g_string_append (string, g_utf8_next_char (text));
2043       *change_case = CHANGE_CASE_NONE;
2044     }
2045   else
2046     {
2047       while (*text != '\0')
2048         {
2049           c = g_utf8_get_char (text);
2050           g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2051           text = g_utf8_next_char (text);
2052         }
2053     }
2054 }
2055
2056 static gboolean
2057 interpolate_replacement (const GMatchInfo *match_info,
2058                          GString          *result,
2059                          gpointer          data)
2060 {
2061   GList *list;
2062   InterpolationData *idata;
2063   gchar *match;
2064   ChangeCase change_case = CHANGE_CASE_NONE;
2065
2066   for (list = data; list; list = list->next)
2067     {
2068       idata = list->data;
2069       switch (idata->type)
2070         {
2071         case REPL_TYPE_STRING:
2072           string_append (result, idata->text, &change_case);
2073           break;
2074         case REPL_TYPE_CHARACTER:
2075           g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2076           if (change_case & CHANGE_CASE_SINGLE_MASK)
2077             change_case = CHANGE_CASE_NONE;
2078           break;
2079         case REPL_TYPE_NUMERIC_REFERENCE:
2080           match = g_match_info_fetch (match_info, idata->num);
2081           if (match)
2082             {
2083               string_append (result, match, &change_case);
2084               g_free (match);
2085             }
2086           break;
2087         case REPL_TYPE_SYMBOLIC_REFERENCE:
2088           match = g_match_info_fetch_named (match_info, idata->text);
2089           if (match)
2090             {
2091               string_append (result, match, &change_case);
2092               g_free (match);
2093             }
2094           break;
2095         case REPL_TYPE_CHANGE_CASE:
2096           change_case = idata->change_case;
2097           break;
2098         }
2099     }
2100
2101   return FALSE; 
2102 }
2103
2104 /* whether actual match_info is needed for replacement, i.e.
2105  * whether there are references
2106  */
2107 static gboolean
2108 interpolation_list_needs_match (GList *list)
2109 {
2110   while (list != NULL)
2111     {
2112       InterpolationData *data = list->data;
2113
2114       if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2115           data->type == REPL_TYPE_NUMERIC_REFERENCE)
2116         {
2117           return TRUE;
2118         }
2119
2120       list = list->next;
2121     }
2122
2123   return FALSE;
2124 }
2125
2126 /**
2127  * g_regex_replace:
2128  * @regex: a #GRegex structure
2129  * @string: the string to perform matches against
2130  * @string_len: the length of @string, or -1 if @string is nul-terminated
2131  * @start_position: starting index of the string to match
2132  * @replacement: text to replace each match with
2133  * @match_options: options for the match
2134  * @error: location to store the error occuring, or %NULL to ignore errors
2135  *
2136  * Replaces all occurances of the pattern in @regex with the
2137  * replacement text. Backreferences of the form '\number' or 
2138  * '\g&lt;number&gt;' in the replacement text are interpolated by the 
2139  * number-th captured subexpression of the match, '\g&lt;name&gt;' refers 
2140  * to the captured subexpression with the given name. '\0' refers to the 
2141  * complete match, but '\0' followed by a number is the octal representation 
2142  * of a character. To include a literal '\' in the replacement, write '\\'.
2143  * There are also escapes that changes the case of the following text:
2144  *
2145  * <variablelist>
2146  * <varlistentry><term>\l</term>
2147  * <listitem>
2148  * <para>Convert to lower case the next character</para>
2149  * </listitem>
2150  * </varlistentry>
2151  * <varlistentry><term>\u</term>
2152  * <listitem>
2153  * <para>Convert to upper case the next character</para>
2154  * </listitem>
2155  * </varlistentry>
2156  * <varlistentry><term>\L</term>
2157  * <listitem>
2158  * <para>Convert to lower case till \E</para>
2159  * </listitem>
2160  * </varlistentry>
2161  * <varlistentry><term>\U</term>
2162  * <listitem>
2163  * <para>Convert to upper case till \E</para>
2164  * </listitem>
2165  * </varlistentry>
2166  * <varlistentry><term>\E</term>
2167  * <listitem>
2168  * <para>End case modification</para>
2169  * </listitem>
2170  * </varlistentry>
2171  * </variablelist>
2172  *
2173  * If you do not need to use backreferences use g_regex_replace_literal().
2174  *
2175  * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2176  * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2177  * you can use g_regex_replace_literal().
2178  *
2179  * Setting @start_position differs from just passing over a shortened 
2180  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that 
2181  * begins with any kind of lookbehind assertion, such as "\b".
2182  *
2183  * Returns: a newly allocated string containing the replacements
2184  *
2185  * Since: 2.14
2186  */
2187 gchar *
2188 g_regex_replace (const GRegex      *regex, 
2189                  const gchar       *string, 
2190                  gssize             string_len,
2191                  gint               start_position,
2192                  const gchar       *replacement,
2193                  GRegexMatchFlags   match_options,
2194                  GError           **error)
2195 {
2196   gchar *result;
2197   GList *list;
2198   GError *tmp_error = NULL;
2199
2200   g_return_val_if_fail (regex != NULL, NULL);
2201   g_return_val_if_fail (string != NULL, NULL);
2202   g_return_val_if_fail (start_position >= 0, NULL);
2203   g_return_val_if_fail (replacement != NULL, NULL);
2204   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2205   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2206
2207   list = split_replacement (replacement, &tmp_error);
2208   if (tmp_error != NULL)
2209     {
2210       g_propagate_error (error, tmp_error);
2211       return NULL;
2212     }
2213
2214   result = g_regex_replace_eval (regex, 
2215                                  string, string_len, start_position,
2216                                  match_options,
2217                                  interpolate_replacement,
2218                                  (gpointer)list,
2219                                  &tmp_error);
2220   if (tmp_error != NULL)
2221     g_propagate_error (error, tmp_error);
2222
2223   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2224   g_list_free (list);
2225
2226   return result;
2227 }
2228
2229 static gboolean
2230 literal_replacement (const GMatchInfo *match_info,
2231                      GString          *result,
2232                      gpointer          data)
2233 {
2234   g_string_append (result, data);
2235   return FALSE;
2236 }
2237
2238 /**
2239  * g_regex_replace_literal:
2240  * @regex: a #GRegex structure
2241  * @string: the string to perform matches against
2242  * @string_len: the length of @string, or -1 if @string is nul-terminated
2243  * @start_position: starting index of the string to match
2244  * @replacement: text to replace each match with
2245  * @match_options: options for the match
2246  * @error: location to store the error occuring, or %NULL to ignore errors
2247  *
2248  * Replaces all occurances of the pattern in @regex with the
2249  * replacement text. @replacement is replaced literally, to
2250  * include backreferences use g_regex_replace().
2251  *
2252  * Setting @start_position differs from just passing over a 
2253  * shortened string and setting #G_REGEX_MATCH_NOTBOL in the 
2254  * case of a pattern that begins with any kind of lookbehind 
2255  * assertion, such as "\b".
2256  *
2257  * Returns: a newly allocated string containing the replacements
2258  *
2259  * Since: 2.14
2260  */
2261 gchar *
2262 g_regex_replace_literal (const GRegex      *regex,
2263                          const gchar       *string,
2264                          gssize             string_len,
2265                          gint               start_position,
2266                          const gchar       *replacement,
2267                          GRegexMatchFlags   match_options,
2268                          GError           **error)
2269 {
2270   g_return_val_if_fail (replacement != NULL, NULL);
2271   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2272
2273   return g_regex_replace_eval (regex,
2274                                string, string_len, start_position,
2275                                match_options,
2276                                literal_replacement,
2277                                (gpointer)replacement,
2278                                error);
2279 }
2280
2281 /**
2282  * g_regex_replace_eval:
2283  * @regex: a #GRegex structure from g_regex_new()
2284  * @string: string to perform matches against
2285  * @string_len: the length of @string, or -1 if @string is nul-terminated
2286  * @start_position: starting index of the string to match
2287  * @match_options: options for the match
2288  * @eval: a function to call for each match
2289  * @user_data: user data to pass to the function
2290  * @error: location to store the error occuring, or %NULL to ignore errors
2291  *
2292  * Replaces occurances of the pattern in regex with the output of 
2293  * @eval for that occurance.
2294  *
2295  * Setting @start_position differs from just passing over a shortened 
2296  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
2297  * that begins with any kind of lookbehind assertion, such as "\b".
2298  *
2299  * Returns: a newly allocated string containing the replacements
2300  *
2301  * Since: 2.14
2302  */
2303 gchar *
2304 g_regex_replace_eval (const GRegex        *regex,
2305                       const gchar         *string,
2306                       gssize               string_len,
2307                       gint                 start_position,
2308                       GRegexMatchFlags     match_options,
2309                       GRegexEvalCallback   eval,
2310                       gpointer             user_data,
2311                       GError             **error)
2312 {
2313   GMatchInfo *match_info;
2314   GString *result;
2315   gint str_pos = 0;
2316   gboolean done = FALSE;
2317   GError *tmp_error = NULL;
2318
2319   g_return_val_if_fail (regex != NULL, NULL);
2320   g_return_val_if_fail (string != NULL, NULL);
2321   g_return_val_if_fail (start_position >= 0, NULL);
2322   g_return_val_if_fail (eval != NULL, NULL);
2323   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2324
2325   if (string_len < 0)
2326     string_len = strlen (string);
2327
2328   result = g_string_sized_new (string_len);
2329
2330   /* run down the string making matches. */
2331   g_regex_match_full (regex, string, string_len, start_position,
2332                       match_options, &match_info, &tmp_error);
2333   while (!done && g_match_info_matches (match_info))
2334     {
2335       g_string_append_len (result,
2336                            string + str_pos,
2337                            match_info->offsets[0] - str_pos);
2338       done = (*eval) (match_info, result, user_data);
2339       str_pos = match_info->offsets[1];
2340       g_match_info_next (match_info, &tmp_error);
2341     }
2342   g_match_info_free (match_info);
2343   if (tmp_error != NULL)
2344     {
2345       g_propagate_error (error, tmp_error);
2346       g_string_free (result, TRUE);
2347       return NULL;
2348     }
2349
2350   g_string_append_len (result, string + str_pos, string_len - str_pos);
2351   return g_string_free (result, FALSE);
2352 }
2353
2354 /**
2355  * g_regex_check_replacement:
2356  * @replacement: the replacement string
2357  * @has_references: location to store information about
2358  *   references in @replacement or %NULL
2359  * @error: location to store error
2360  *
2361  * Checks whether @replacement is a valid replacement string 
2362  * (see g_regex_replace()), i.e. that all escape sequences in 
2363  * it are valid.
2364  *
2365  * If @has_references is not %NULL then @replacement is checked 
2366  * for pattern references. For instance, replacement text 'foo\n'
2367  * does not contain references and may be evaluated without information
2368  * about actual match, but '\0\1' (whole match followed by first 
2369  * subpattern) requires valid #GMatchInfo object.
2370  *
2371  * Returns: whether @replacement is a valid replacement string
2372  *
2373  * Since: 2.14
2374  */
2375 gboolean
2376 g_regex_check_replacement (const gchar  *replacement,
2377                            gboolean     *has_references,
2378                            GError      **error)
2379 {
2380   GList *list;
2381   GError *tmp = NULL;
2382
2383   list = split_replacement (replacement, &tmp);
2384
2385   if (tmp)
2386   {
2387     g_propagate_error (error, tmp);
2388     return FALSE;
2389   }
2390
2391   if (has_references)
2392     *has_references = interpolation_list_needs_match (list);
2393
2394   g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2395   g_list_free (list);
2396
2397   return TRUE;
2398 }
2399
2400 /**
2401  * g_regex_escape_string:
2402  * @string: the string to escape
2403  * @length: the length of @string, or -1 if @string is nul-terminated
2404  *
2405  * Escapes the special characters used for regular expressions 
2406  * in @string, for instance "a.b*c" becomes "a\.b\*c". This 
2407  * function is useful to dynamically generate regular expressions.
2408  *
2409  * @string can contain nul characters that are replaced with "\0", 
2410  * in this case remember to specify the correct length of @string 
2411  * in @length.
2412  *
2413  * Returns: a newly-allocated escaped string
2414  *
2415  * Since: 2.14
2416  */
2417 gchar *
2418 g_regex_escape_string (const gchar *string,
2419                        gint         length)
2420 {
2421   GString *escaped;
2422   const char *p, *piece_start, *end;
2423
2424   g_return_val_if_fail (string != NULL, NULL);
2425
2426   if (length < 0)
2427     length = strlen (string);
2428
2429   end = string + length;
2430   p = piece_start = string;
2431   escaped = g_string_sized_new (length + 1);
2432
2433   while (p < end)
2434     {
2435       switch (*p)
2436         {
2437         case '\0':
2438         case '\\':
2439         case '|':
2440         case '(':
2441         case ')':
2442         case '[':
2443         case ']':
2444         case '{':
2445         case '}':
2446         case '^':
2447         case '$':
2448         case '*':
2449         case '+':
2450         case '?':
2451         case '.':
2452           if (p != piece_start)
2453             /* copy the previous piece. */
2454             g_string_append_len (escaped, piece_start, p - piece_start);
2455           g_string_append_c (escaped, '\\');
2456           if (*p == '\0')
2457             g_string_append_c (escaped, '0');
2458           else
2459             g_string_append_c (escaped, *p);
2460           piece_start = ++p;
2461           break;
2462         default:
2463           p = g_utf8_next_char (p);
2464           break;
2465         } 
2466   }
2467
2468   if (piece_start < end)
2469     g_string_append_len (escaped, piece_start, end - piece_start);
2470
2471   return g_string_free (escaped, FALSE);
2472 }
2473
2474 #define __G_REGEX_C__
2475 #include "galiasdef.c"