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