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