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