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