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