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