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