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