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