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