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