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