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