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