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