blob: 36f5bb456636a04b9f0a79d2e066886d38c0620f [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * Handling of regular expressions: vim_regcomp(), vim_regexec(), vim_regsub()
4 *
5 * NOTICE:
6 *
7 * This is NOT the original regular expression code as written by Henry
8 * Spencer. This code has been modified specifically for use with the VIM
9 * editor, and should not be used separately from Vim. If you want a good
10 * regular expression library, get the original code. The copyright notice
11 * that follows is from the original.
12 *
13 * END NOTICE
14 *
15 * Copyright (c) 1986 by University of Toronto.
16 * Written by Henry Spencer. Not derived from licensed software.
17 *
18 * Permission is granted to anyone to use this software for any
19 * purpose on any computer system, and to redistribute it freely,
20 * subject to the following restrictions:
21 *
22 * 1. The author is not responsible for the consequences of use of
23 * this software, no matter how awful, even if they arise
24 * from defects in it.
25 *
26 * 2. The origin of this software must not be misrepresented, either
27 * by explicit claim or by omission.
28 *
29 * 3. Altered versions must be plainly marked as such, and must not
30 * be misrepresented as being the original software.
31 *
32 * Beware that some of this code is subtly aware of the way operator
33 * precedence is structured in regular expressions. Serious changes in
34 * regular-expression syntax might require a total rethink.
35 *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000036 * Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert
37 * Webb, Ciaran McCreesh and Bram Moolenaar.
Bram Moolenaar071d4272004-06-13 20:20:40 +000038 * Named character class support added by Walter Briscoe (1998 Jul 01)
39 */
40
41#include "vim.h"
42
43#undef DEBUG
44
45/*
46 * The "internal use only" fields in regexp.h are present to pass info from
47 * compile to execute that permits the execute phase to run lots faster on
48 * simple cases. They are:
49 *
50 * regstart char that must begin a match; NUL if none obvious; Can be a
51 * multi-byte character.
52 * reganch is the match anchored (at beginning-of-line only)?
53 * regmust string (pointer into program) that match must include, or NULL
54 * regmlen length of regmust string
55 * regflags RF_ values or'ed together
56 *
57 * Regstart and reganch permit very fast decisions on suitable starting points
58 * for a match, cutting down the work a lot. Regmust permits fast rejection
59 * of lines that cannot possibly match. The regmust tests are costly enough
60 * that vim_regcomp() supplies a regmust only if the r.e. contains something
61 * potentially expensive (at present, the only such thing detected is * or +
62 * at the start of the r.e., which can involve a lot of backup). Regmlen is
63 * supplied because the test in vim_regexec() needs it and vim_regcomp() is
64 * computing it anyway.
65 */
66
67/*
68 * Structure for regexp "program". This is essentially a linear encoding
69 * of a nondeterministic finite-state machine (aka syntax charts or
70 * "railroad normal form" in parsing technology). Each node is an opcode
71 * plus a "next" pointer, possibly plus an operand. "Next" pointers of
72 * all nodes except BRANCH and BRACES_COMPLEX implement concatenation; a "next"
73 * pointer with a BRANCH on both ends of it is connecting two alternatives.
74 * (Here we have one of the subtle syntax dependencies: an individual BRANCH
75 * (as opposed to a collection of them) is never concatenated with anything
76 * because of operator precedence). The "next" pointer of a BRACES_COMPLEX
Bram Moolenaardf177f62005-02-22 08:39:57 +000077 * node points to the node after the stuff to be repeated.
78 * The operand of some types of node is a literal string; for others, it is a
79 * node leading into a sub-FSM. In particular, the operand of a BRANCH node
80 * is the first node of the branch.
81 * (NB this is *not* a tree structure: the tail of the branch connects to the
82 * thing following the set of BRANCHes.)
Bram Moolenaar071d4272004-06-13 20:20:40 +000083 *
84 * pattern is coded like:
85 *
86 * +-----------------+
87 * | V
88 * <aa>\|<bb> BRANCH <aa> BRANCH <bb> --> END
89 * | ^ | ^
90 * +------+ +----------+
91 *
92 *
93 * +------------------+
94 * V |
95 * <aa>* BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
96 * | | ^ ^
97 * | +---------------+ |
98 * +---------------------------------------------+
99 *
100 *
Bram Moolenaardf177f62005-02-22 08:39:57 +0000101 * +----------------------+
102 * V |
Bram Moolenaar19a09a12005-03-04 23:39:37 +0000103 * <aa>\+ BRANCH <aa> --> BRANCH --> BACKP BRANCH --> NOTHING --> END
104 * | | ^ ^
105 * | +-----------+ |
106 * +--------------------------------------------------+
Bram Moolenaardf177f62005-02-22 08:39:57 +0000107 *
108 *
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109 * +-------------------------+
110 * V |
111 * <aa>\{} BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK END
112 * | | ^
113 * | +----------------+
114 * +-----------------------------------------------+
115 *
116 *
117 * <aa>\@!<bb> BRANCH NOMATCH <aa> --> END <bb> --> END
118 * | | ^ ^
119 * | +----------------+ |
120 * +--------------------------------+
121 *
122 * +---------+
123 * | V
124 * \z[abc] BRANCH BRANCH a BRANCH b BRANCH c BRANCH NOTHING --> END
125 * | | | | ^ ^
126 * | | | +-----+ |
127 * | | +----------------+ |
128 * | +---------------------------+ |
129 * +------------------------------------------------------+
130 *
131 * They all start with a BRANCH for "\|" alternaties, even when there is only
132 * one alternative.
133 */
134
135/*
136 * The opcodes are:
137 */
138
139/* definition number opnd? meaning */
140#define END 0 /* End of program or NOMATCH operand. */
141#define BOL 1 /* Match "" at beginning of line. */
142#define EOL 2 /* Match "" at end of line. */
143#define BRANCH 3 /* node Match this alternative, or the
144 * next... */
145#define BACK 4 /* Match "", "next" ptr points backward. */
146#define EXACTLY 5 /* str Match this string. */
147#define NOTHING 6 /* Match empty string. */
148#define STAR 7 /* node Match this (simple) thing 0 or more
149 * times. */
150#define PLUS 8 /* node Match this (simple) thing 1 or more
151 * times. */
152#define MATCH 9 /* node match the operand zero-width */
153#define NOMATCH 10 /* node check for no match with operand */
154#define BEHIND 11 /* node look behind for a match with operand */
155#define NOBEHIND 12 /* node look behind for no match with operand */
156#define SUBPAT 13 /* node match the operand here */
157#define BRACE_SIMPLE 14 /* node Match this (simple) thing between m and
158 * n times (\{m,n\}). */
159#define BOW 15 /* Match "" after [^a-zA-Z0-9_] */
160#define EOW 16 /* Match "" at [^a-zA-Z0-9_] */
161#define BRACE_LIMITS 17 /* nr nr define the min & max for BRACE_SIMPLE
162 * and BRACE_COMPLEX. */
163#define NEWL 18 /* Match line-break */
164#define BHPOS 19 /* End position for BEHIND or NOBEHIND */
165
166
167/* character classes: 20-48 normal, 50-78 include a line-break */
168#define ADD_NL 30
169#define FIRST_NL ANY + ADD_NL
170#define ANY 20 /* Match any one character. */
171#define ANYOF 21 /* str Match any character in this string. */
172#define ANYBUT 22 /* str Match any character not in this
173 * string. */
174#define IDENT 23 /* Match identifier char */
175#define SIDENT 24 /* Match identifier char but no digit */
176#define KWORD 25 /* Match keyword char */
177#define SKWORD 26 /* Match word char but no digit */
178#define FNAME 27 /* Match file name char */
179#define SFNAME 28 /* Match file name char but no digit */
180#define PRINT 29 /* Match printable char */
181#define SPRINT 30 /* Match printable char but no digit */
182#define WHITE 31 /* Match whitespace char */
183#define NWHITE 32 /* Match non-whitespace char */
184#define DIGIT 33 /* Match digit char */
185#define NDIGIT 34 /* Match non-digit char */
186#define HEX 35 /* Match hex char */
187#define NHEX 36 /* Match non-hex char */
188#define OCTAL 37 /* Match octal char */
189#define NOCTAL 38 /* Match non-octal char */
190#define WORD 39 /* Match word char */
191#define NWORD 40 /* Match non-word char */
192#define HEAD 41 /* Match head char */
193#define NHEAD 42 /* Match non-head char */
194#define ALPHA 43 /* Match alpha char */
195#define NALPHA 44 /* Match non-alpha char */
196#define LOWER 45 /* Match lowercase char */
197#define NLOWER 46 /* Match non-lowercase char */
198#define UPPER 47 /* Match uppercase char */
199#define NUPPER 48 /* Match non-uppercase char */
200#define LAST_NL NUPPER + ADD_NL
201#define WITH_NL(op) ((op) >= FIRST_NL && (op) <= LAST_NL)
202
203#define MOPEN 80 /* -89 Mark this point in input as start of
204 * \( subexpr. MOPEN + 0 marks start of
205 * match. */
206#define MCLOSE 90 /* -99 Analogous to MOPEN. MCLOSE + 0 marks
207 * end of match. */
208#define BACKREF 100 /* -109 node Match same string again \1-\9 */
209
210#ifdef FEAT_SYN_HL
211# define ZOPEN 110 /* -119 Mark this point in input as start of
212 * \z( subexpr. */
213# define ZCLOSE 120 /* -129 Analogous to ZOPEN. */
214# define ZREF 130 /* -139 node Match external submatch \z1-\z9 */
215#endif
216
217#define BRACE_COMPLEX 140 /* -149 node Match nodes between m & n times */
218
219#define NOPEN 150 /* Mark this point in input as start of
220 \%( subexpr. */
221#define NCLOSE 151 /* Analogous to NOPEN. */
222
223#define MULTIBYTECODE 200 /* mbc Match one multi-byte character */
224#define RE_BOF 201 /* Match "" at beginning of file. */
225#define RE_EOF 202 /* Match "" at end of file. */
226#define CURSOR 203 /* Match location of cursor. */
227
228#define RE_LNUM 204 /* nr cmp Match line number */
229#define RE_COL 205 /* nr cmp Match column number */
230#define RE_VCOL 206 /* nr cmp Match virtual column number */
231
Bram Moolenaar19a09a12005-03-04 23:39:37 +0000232#define BACKP 207 /* Like BACK but for \+ */
233
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234/*
235 * Magic characters have a special meaning, they don't match literally.
236 * Magic characters are negative. This separates them from literal characters
237 * (possibly multi-byte). Only ASCII characters can be Magic.
238 */
239#define Magic(x) ((int)(x) - 256)
240#define un_Magic(x) ((x) + 256)
241#define is_Magic(x) ((x) < 0)
242
243static int no_Magic __ARGS((int x));
244static int toggle_Magic __ARGS((int x));
245
246 static int
247no_Magic(x)
248 int x;
249{
250 if (is_Magic(x))
251 return un_Magic(x);
252 return x;
253}
254
255 static int
256toggle_Magic(x)
257 int x;
258{
259 if (is_Magic(x))
260 return un_Magic(x);
261 return Magic(x);
262}
263
264/*
265 * The first byte of the regexp internal "program" is actually this magic
266 * number; the start node begins in the second byte. It's used to catch the
267 * most severe mutilation of the program by the caller.
268 */
269
270#define REGMAGIC 0234
271
272/*
273 * Opcode notes:
274 *
275 * BRANCH The set of branches constituting a single choice are hooked
276 * together with their "next" pointers, since precedence prevents
277 * anything being concatenated to any individual branch. The
278 * "next" pointer of the last BRANCH in a choice points to the
279 * thing following the whole choice. This is also where the
280 * final "next" pointer of each individual branch points; each
281 * branch starts with the operand node of a BRANCH node.
282 *
283 * BACK Normal "next" pointers all implicitly point forward; BACK
284 * exists to make loop structures possible.
285 *
Bram Moolenaar19a09a12005-03-04 23:39:37 +0000286 * BACKP Like BACK, but used for \+. Doesn't check for an empty match.
287 *
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288 * STAR,PLUS '=', and complex '*' and '+', are implemented as circular
289 * BRANCH structures using BACK. Simple cases (one character
290 * per match) are implemented with STAR and PLUS for speed
291 * and to minimize recursive plunges.
292 *
293 * BRACE_LIMITS This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
294 * node, and defines the min and max limits to be used for that
295 * node.
296 *
297 * MOPEN,MCLOSE ...are numbered at compile time.
298 * ZOPEN,ZCLOSE ...ditto
299 */
300
301/*
302 * A node is one char of opcode followed by two chars of "next" pointer.
303 * "Next" pointers are stored as two 8-bit bytes, high order first. The
304 * value is a positive offset from the opcode of the node containing it.
305 * An operand, if any, simply follows the node. (Note that much of the
306 * code generation knows about this implicit relationship.)
307 *
308 * Using two bytes for the "next" pointer is vast overkill for most things,
309 * but allows patterns to get big without disasters.
310 */
311#define OP(p) ((int)*(p))
312#define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
313#define OPERAND(p) ((p) + 3)
314/* Obtain an operand that was stored as four bytes, MSB first. */
315#define OPERAND_MIN(p) (((long)(p)[3] << 24) + ((long)(p)[4] << 16) \
316 + ((long)(p)[5] << 8) + (long)(p)[6])
317/* Obtain a second operand stored as four bytes. */
318#define OPERAND_MAX(p) OPERAND_MIN((p) + 4)
319/* Obtain a second single-byte operand stored after a four bytes operand. */
320#define OPERAND_CMP(p) (p)[7]
321
322/*
323 * Utility definitions.
324 */
325#define UCHARAT(p) ((int)*(char_u *)(p))
326
327/* Used for an error (down from) vim_regcomp(): give the error message, set
328 * rc_did_emsg and return NULL */
329#define EMSG_RET_NULL(m) { EMSG(m); rc_did_emsg = TRUE; return NULL; }
330#define EMSG_M_RET_NULL(m, c) { EMSG2(m, c ? "" : "\\"); rc_did_emsg = TRUE; return NULL; }
331#define EMSG_RET_FAIL(m) { EMSG(m); rc_did_emsg = TRUE; return FAIL; }
332#define EMSG_ONE_RET_NULL EMSG_M_RET_NULL(_("E369: invalid item in %s%%[]"), reg_magic == MAGIC_ALL)
333
334#define MAX_LIMIT (32767L << 16L)
335
336static int re_multi_type __ARGS((int));
337static int cstrncmp __ARGS((char_u *s1, char_u *s2, int *n));
338static char_u *cstrchr __ARGS((char_u *, int));
339
340#ifdef DEBUG
341static void regdump __ARGS((char_u *, regprog_T *));
342static char_u *regprop __ARGS((char_u *));
343#endif
344
345#define NOT_MULTI 0
346#define MULTI_ONE 1
347#define MULTI_MULT 2
348/*
349 * Return NOT_MULTI if c is not a "multi" operator.
350 * Return MULTI_ONE if c is a single "multi" operator.
351 * Return MULTI_MULT if c is a multi "multi" operator.
352 */
353 static int
354re_multi_type(c)
355 int c;
356{
357 if (c == Magic('@') || c == Magic('=') || c == Magic('?'))
358 return MULTI_ONE;
359 if (c == Magic('*') || c == Magic('+') || c == Magic('{'))
360 return MULTI_MULT;
361 return NOT_MULTI;
362}
363
364/*
365 * Flags to be passed up and down.
366 */
367#define HASWIDTH 0x1 /* Known never to match null string. */
368#define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
369#define SPSTART 0x4 /* Starts with * or +. */
370#define HASNL 0x8 /* Contains some \n. */
371#define HASLOOKBH 0x10 /* Contains "\@<=" or "\@<!". */
372#define WORST 0 /* Worst case. */
373
374/*
375 * When regcode is set to this value, code is not emitted and size is computed
376 * instead.
377 */
378#define JUST_CALC_SIZE ((char_u *) -1)
379
380static char_u *reg_prev_sub;
381
382/*
383 * REGEXP_INRANGE contains all characters which are always special in a []
384 * range after '\'.
385 * REGEXP_ABBR contains all characters which act as abbreviations after '\'.
386 * These are:
387 * \n - New line (NL).
388 * \r - Carriage Return (CR).
389 * \t - Tab (TAB).
390 * \e - Escape (ESC).
391 * \b - Backspace (Ctrl_H).
Bram Moolenaarc0197e22004-09-13 20:26:32 +0000392 * \d - Character code in decimal, eg \d123
393 * \o - Character code in octal, eg \o80
394 * \x - Character code in hex, eg \x4a
395 * \u - Multibyte character code, eg \u20ac
396 * \U - Long multibyte character code, eg \U12345678
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 */
398static char_u REGEXP_INRANGE[] = "]^-n\\";
Bram Moolenaarc0197e22004-09-13 20:26:32 +0000399static char_u REGEXP_ABBR[] = "nrtebdoxuU";
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400
401static int backslash_trans __ARGS((int c));
Bram Moolenaardf177f62005-02-22 08:39:57 +0000402static int get_char_class __ARGS((char_u **pp));
403static int get_equi_class __ARGS((char_u **pp));
404static void reg_equi_class __ARGS((int c));
405static int get_coll_element __ARGS((char_u **pp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406static char_u *skip_anyof __ARGS((char_u *p));
407static void init_class_tab __ARGS((void));
408
409/*
410 * Translate '\x' to its control character, except "\n", which is Magic.
411 */
412 static int
413backslash_trans(c)
414 int c;
415{
416 switch (c)
417 {
418 case 'r': return CAR;
419 case 't': return TAB;
420 case 'e': return ESC;
421 case 'b': return BS;
422 }
423 return c;
424}
425
426/*
Bram Moolenaardf177f62005-02-22 08:39:57 +0000427 * Check for a character class name "[:name:]". "pp" points to the '['.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 * Returns one of the CLASS_ items. CLASS_NONE means that no item was
429 * recognized. Otherwise "pp" is advanced to after the item.
430 */
431 static int
Bram Moolenaardf177f62005-02-22 08:39:57 +0000432get_char_class(pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 char_u **pp;
434{
435 static const char *(class_names[]) =
436 {
437 "alnum:]",
438#define CLASS_ALNUM 0
439 "alpha:]",
440#define CLASS_ALPHA 1
441 "blank:]",
442#define CLASS_BLANK 2
443 "cntrl:]",
444#define CLASS_CNTRL 3
445 "digit:]",
446#define CLASS_DIGIT 4
447 "graph:]",
448#define CLASS_GRAPH 5
449 "lower:]",
450#define CLASS_LOWER 6
451 "print:]",
452#define CLASS_PRINT 7
453 "punct:]",
454#define CLASS_PUNCT 8
455 "space:]",
456#define CLASS_SPACE 9
457 "upper:]",
458#define CLASS_UPPER 10
459 "xdigit:]",
460#define CLASS_XDIGIT 11
461 "tab:]",
462#define CLASS_TAB 12
463 "return:]",
464#define CLASS_RETURN 13
465 "backspace:]",
466#define CLASS_BACKSPACE 14
467 "escape:]",
468#define CLASS_ESCAPE 15
469 };
470#define CLASS_NONE 99
471 int i;
472
473 if ((*pp)[1] == ':')
474 {
475 for (i = 0; i < sizeof(class_names) / sizeof(*class_names); ++i)
476 if (STRNCMP(*pp + 2, class_names[i], STRLEN(class_names[i])) == 0)
477 {
478 *pp += STRLEN(class_names[i]) + 2;
479 return i;
480 }
481 }
482 return CLASS_NONE;
483}
484
485/*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 * Specific version of character class functions.
487 * Using a table to keep this fast.
488 */
489static short class_tab[256];
490
491#define RI_DIGIT 0x01
492#define RI_HEX 0x02
493#define RI_OCTAL 0x04
494#define RI_WORD 0x08
495#define RI_HEAD 0x10
496#define RI_ALPHA 0x20
497#define RI_LOWER 0x40
498#define RI_UPPER 0x80
499#define RI_WHITE 0x100
500
501 static void
502init_class_tab()
503{
504 int i;
505 static int done = FALSE;
506
507 if (done)
508 return;
509
510 for (i = 0; i < 256; ++i)
511 {
512 if (i >= '0' && i <= '7')
513 class_tab[i] = RI_DIGIT + RI_HEX + RI_OCTAL + RI_WORD;
514 else if (i >= '8' && i <= '9')
515 class_tab[i] = RI_DIGIT + RI_HEX + RI_WORD;
516 else if (i >= 'a' && i <= 'f')
517 class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
518#ifdef EBCDIC
519 else if ((i >= 'g' && i <= 'i') || (i >= 'j' && i <= 'r')
520 || (i >= 's' && i <= 'z'))
521#else
522 else if (i >= 'g' && i <= 'z')
523#endif
524 class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
525 else if (i >= 'A' && i <= 'F')
526 class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
527#ifdef EBCDIC
528 else if ((i >= 'G' && i <= 'I') || ( i >= 'J' && i <= 'R')
529 || (i >= 'S' && i <= 'Z'))
530#else
531 else if (i >= 'G' && i <= 'Z')
532#endif
533 class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
534 else if (i == '_')
535 class_tab[i] = RI_WORD + RI_HEAD;
536 else
537 class_tab[i] = 0;
538 }
539 class_tab[' '] |= RI_WHITE;
540 class_tab['\t'] |= RI_WHITE;
541 done = TRUE;
542}
543
544#ifdef FEAT_MBYTE
545# define ri_digit(c) (c < 0x100 && (class_tab[c] & RI_DIGIT))
546# define ri_hex(c) (c < 0x100 && (class_tab[c] & RI_HEX))
547# define ri_octal(c) (c < 0x100 && (class_tab[c] & RI_OCTAL))
548# define ri_word(c) (c < 0x100 && (class_tab[c] & RI_WORD))
549# define ri_head(c) (c < 0x100 && (class_tab[c] & RI_HEAD))
550# define ri_alpha(c) (c < 0x100 && (class_tab[c] & RI_ALPHA))
551# define ri_lower(c) (c < 0x100 && (class_tab[c] & RI_LOWER))
552# define ri_upper(c) (c < 0x100 && (class_tab[c] & RI_UPPER))
553# define ri_white(c) (c < 0x100 && (class_tab[c] & RI_WHITE))
554#else
555# define ri_digit(c) (class_tab[c] & RI_DIGIT)
556# define ri_hex(c) (class_tab[c] & RI_HEX)
557# define ri_octal(c) (class_tab[c] & RI_OCTAL)
558# define ri_word(c) (class_tab[c] & RI_WORD)
559# define ri_head(c) (class_tab[c] & RI_HEAD)
560# define ri_alpha(c) (class_tab[c] & RI_ALPHA)
561# define ri_lower(c) (class_tab[c] & RI_LOWER)
562# define ri_upper(c) (class_tab[c] & RI_UPPER)
563# define ri_white(c) (class_tab[c] & RI_WHITE)
564#endif
565
566/* flags for regflags */
567#define RF_ICASE 1 /* ignore case */
568#define RF_NOICASE 2 /* don't ignore case */
569#define RF_HASNL 4 /* can match a NL */
570#define RF_ICOMBINE 8 /* ignore combining characters */
571#define RF_LOOKBH 16 /* uses "\@<=" or "\@<!" */
572
573/*
574 * Global work variables for vim_regcomp().
575 */
576
577static char_u *regparse; /* Input-scan pointer. */
578static int prevchr_len; /* byte length of previous char */
579static int num_complex_braces; /* Complex \{...} count */
580static int regnpar; /* () count. */
581#ifdef FEAT_SYN_HL
582static int regnzpar; /* \z() count. */
583static int re_has_z; /* \z item detected */
584#endif
585static char_u *regcode; /* Code-emit pointer, or JUST_CALC_SIZE */
586static long regsize; /* Code size. */
587static char_u had_endbrace[NSUBEXP]; /* flags, TRUE if end of () found */
588static unsigned regflags; /* RF_ flags for prog */
589static long brace_min[10]; /* Minimums for complex brace repeats */
590static long brace_max[10]; /* Maximums for complex brace repeats */
591static int brace_count[10]; /* Current counts for complex brace repeats */
592#if defined(FEAT_SYN_HL) || defined(PROTO)
593static int had_eol; /* TRUE when EOL found by vim_regcomp() */
594#endif
595static int one_exactly = FALSE; /* only do one char for EXACTLY */
596
597static int reg_magic; /* magicness of the pattern: */
598#define MAGIC_NONE 1 /* "\V" very unmagic */
599#define MAGIC_OFF 2 /* "\M" or 'magic' off */
600#define MAGIC_ON 3 /* "\m" or 'magic' */
601#define MAGIC_ALL 4 /* "\v" very magic */
602
603static int reg_string; /* matching with a string instead of a buffer
604 line */
605
606/*
607 * META contains all characters that may be magic, except '^' and '$'.
608 */
609
610#ifdef EBCDIC
611static char_u META[] = "%&()*+.123456789<=>?@ACDFHIKLMOPSUVWX[_acdfhiklmnopsuvwxz{|~";
612#else
613/* META[] is used often enough to justify turning it into a table. */
614static char_u META_flags[] = {
615 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
616 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
617/* % & ( ) * + . */
618 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
619/* 1 2 3 4 5 6 7 8 9 < = > ? */
620 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
621/* @ A C D F H I K L M O */
622 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
623/* P S U V W X Z [ _ */
624 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1,
625/* a c d f h i k l m n o */
626 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
627/* p s u v w x z { | ~ */
628 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
629};
630#endif
631
632static int curchr;
633
634/* arguments for reg() */
635#define REG_NOPAREN 0 /* toplevel reg() */
636#define REG_PAREN 1 /* \(\) */
637#define REG_ZPAREN 2 /* \z(\) */
638#define REG_NPAREN 3 /* \%(\) */
639
640/*
641 * Forward declarations for vim_regcomp()'s friends.
642 */
643static void initchr __ARGS((char_u *));
644static int getchr __ARGS((void));
645static void skipchr_keepstart __ARGS((void));
646static int peekchr __ARGS((void));
647static void skipchr __ARGS((void));
648static void ungetchr __ARGS((void));
Bram Moolenaarc0197e22004-09-13 20:26:32 +0000649static int gethexchrs __ARGS((int maxinputlen));
650static int getoctchrs __ARGS((void));
651static int getdecchrs __ARGS((void));
652static int coll_get_char __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653static void regcomp_start __ARGS((char_u *expr, int flags));
654static char_u *reg __ARGS((int, int *));
655static char_u *regbranch __ARGS((int *flagp));
656static char_u *regconcat __ARGS((int *flagp));
657static char_u *regpiece __ARGS((int *));
658static char_u *regatom __ARGS((int *));
659static char_u *regnode __ARGS((int));
660static int prog_magic_wrong __ARGS((void));
661static char_u *regnext __ARGS((char_u *));
662static void regc __ARGS((int b));
663#ifdef FEAT_MBYTE
664static void regmbc __ARGS((int c));
Bram Moolenaardf177f62005-02-22 08:39:57 +0000665#else
666# define regmbc(c) regc(c)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667#endif
668static void reginsert __ARGS((int, char_u *));
669static void reginsert_limits __ARGS((int, long, long, char_u *));
670static char_u *re_put_long __ARGS((char_u *pr, long_u val));
671static int read_limits __ARGS((long *, long *));
672static void regtail __ARGS((char_u *, char_u *));
673static void regoptail __ARGS((char_u *, char_u *));
674
675/*
676 * Return TRUE if compiled regular expression "prog" can match a line break.
677 */
678 int
679re_multiline(prog)
680 regprog_T *prog;
681{
682 return (prog->regflags & RF_HASNL);
683}
684
685/*
686 * Return TRUE if compiled regular expression "prog" looks before the start
687 * position (pattern contains "\@<=" or "\@<!").
688 */
689 int
690re_lookbehind(prog)
691 regprog_T *prog;
692{
693 return (prog->regflags & RF_LOOKBH);
694}
695
696/*
Bram Moolenaardf177f62005-02-22 08:39:57 +0000697 * Check for an equivalence class name "[=a=]". "pp" points to the '['.
698 * Returns a character representing the class. Zero means that no item was
699 * recognized. Otherwise "pp" is advanced to after the item.
700 */
701 static int
702get_equi_class(pp)
703 char_u **pp;
704{
705 int c;
706 int l = 1;
707 char_u *p = *pp;
708
709 if (p[1] == '=')
710 {
711#ifdef FEAT_MBYTE
712 if (has_mbyte)
713 l = mb_ptr2len_check(p + 2);
714#endif
715 if (p[l + 2] == '=' && p[l + 3] == ']')
716 {
717#ifdef FEAT_MBYTE
718 if (has_mbyte)
719 c = mb_ptr2char(p + 2);
720 else
721#endif
722 c = p[2];
723 *pp += l + 4;
724 return c;
725 }
726 }
727 return 0;
728}
729
730/*
731 * Produce the bytes for equivalence class "c".
732 * Currently only handles latin1, latin9 and utf-8.
733 */
734 static void
735reg_equi_class(c)
736 int c;
737{
738#ifdef FEAT_MBYTE
739 if (enc_utf8 || STRCMP(p_enc, "latin1") == 0
740 || STRCMP(p_enc, "latin9") == 0)
741#endif
742 {
743 switch (c)
744 {
745 case 'A': case 'À': case 'Á': case 'Â':
746 case 'Ã': case 'Ä': case 'Å':
747 regmbc('A'); regmbc('À'); regmbc('Á'); regmbc('Â');
748 regmbc('Ã'); regmbc('Ä'); regmbc('Å');
749 return;
750 case 'C': case 'Ç':
751 regmbc('C'); regmbc('Ç');
752 return;
753 case 'E': case 'È': case 'É': case 'Ê': case 'Ë':
754 regmbc('E'); regmbc('È'); regmbc('É'); regmbc('Ê');
755 regmbc('Ë');
756 return;
757 case 'I': case 'Ì': case 'Í': case 'Î': case 'Ï':
758 regmbc('I'); regmbc('Ì'); regmbc('Í'); regmbc('Î');
759 regmbc('Ï');
760 return;
761 case 'N': case 'Ñ':
762 regmbc('N'); regmbc('Ñ');
763 return;
764 case 'O': case 'Ò': case 'Ó': case 'Ô': case 'Õ': case 'Ö':
765 regmbc('O'); regmbc('Ò'); regmbc('Ó'); regmbc('Ô');
766 regmbc('Õ'); regmbc('Ö');
767 return;
768 case 'U': case 'Ù': case 'Ú': case 'Û': case 'Ü':
769 regmbc('U'); regmbc('Ù'); regmbc('Ú'); regmbc('Û');
770 regmbc('Ü');
771 return;
772 case 'Y': case 'Ý':
773 regmbc('Y'); regmbc('Ý');
774 return;
775 case 'a': case 'à': case 'á': case 'â':
776 case 'ã': case 'ä': case 'å':
777 regmbc('a'); regmbc('à'); regmbc('á'); regmbc('â');
778 regmbc('ã'); regmbc('ä'); regmbc('å');
779 return;
780 case 'c': case 'ç':
781 regmbc('c'); regmbc('ç');
782 return;
783 case 'e': case 'è': case 'é': case 'ê': case 'ë':
784 regmbc('e'); regmbc('è'); regmbc('é'); regmbc('ê');
785 regmbc('ë');
786 return;
787 case 'i': case 'ì': case 'í': case 'î': case 'ï':
788 regmbc('i'); regmbc('ì'); regmbc('í'); regmbc('î');
789 regmbc('ï');
790 return;
791 case 'n': case 'ñ':
792 regmbc('n'); regmbc('ñ');
793 return;
794 case 'o': case 'ò': case 'ó': case 'ô': case 'õ': case 'ö':
795 regmbc('o'); regmbc('ò'); regmbc('ó'); regmbc('ô');
796 regmbc('õ'); regmbc('ö');
797 return;
798 case 'u': case 'ù': case 'ú': case 'û': case 'ü':
799 regmbc('u'); regmbc('ù'); regmbc('ú'); regmbc('û');
800 regmbc('ü');
801 return;
802 case 'y': case 'ý': case 'ÿ':
803 regmbc('y'); regmbc('ý'); regmbc('ÿ');
804 return;
805 }
806 }
807 regmbc(c);
808}
809
810/*
811 * Check for a collating element "[.a.]". "pp" points to the '['.
812 * Returns a character. Zero means that no item was recognized. Otherwise
813 * "pp" is advanced to after the item.
814 * Currently only single characters are recognized!
815 */
816 static int
817get_coll_element(pp)
818 char_u **pp;
819{
820 int c;
821 int l = 1;
822 char_u *p = *pp;
823
824 if (p[1] == '.')
825 {
826#ifdef FEAT_MBYTE
827 if (has_mbyte)
828 l = mb_ptr2len_check(p + 2);
829#endif
830 if (p[l + 2] == '.' && p[l + 3] == ']')
831 {
832#ifdef FEAT_MBYTE
833 if (has_mbyte)
834 c = mb_ptr2char(p + 2);
835 else
836#endif
837 c = p[2];
838 *pp += l + 4;
839 return c;
840 }
841 }
842 return 0;
843}
844
845
846/*
847 * Skip over a "[]" range.
848 * "p" must point to the character after the '['.
849 * The returned pointer is on the matching ']', or the terminating NUL.
850 */
851 static char_u *
852skip_anyof(p)
853 char_u *p;
854{
855 int cpo_lit; /* 'cpoptions' contains 'l' flag */
856 int cpo_bsl; /* 'cpoptions' contains '\' flag */
857#ifdef FEAT_MBYTE
858 int l;
859#endif
860
861 cpo_lit = (!reg_syn && vim_strchr(p_cpo, CPO_LITERAL) != NULL);
862 cpo_bsl = (!reg_syn && vim_strchr(p_cpo, CPO_BACKSL) != NULL);
863
864 if (*p == '^') /* Complement of range. */
865 ++p;
866 if (*p == ']' || *p == '-')
867 ++p;
868 while (*p != NUL && *p != ']')
869 {
870#ifdef FEAT_MBYTE
871 if (has_mbyte && (l = (*mb_ptr2len_check)(p)) > 1)
872 p += l;
873 else
874#endif
875 if (*p == '-')
876 {
877 ++p;
878 if (*p != ']' && *p != NUL)
879 mb_ptr_adv(p);
880 }
881 else if (*p == '\\'
882 && !cpo_bsl
883 && (vim_strchr(REGEXP_INRANGE, p[1]) != NULL
884 || (!cpo_lit && vim_strchr(REGEXP_ABBR, p[1]) != NULL)))
885 p += 2;
886 else if (*p == '[')
887 {
888 if (get_char_class(&p) == CLASS_NONE
889 && get_equi_class(&p) == 0
890 && get_coll_element(&p) == 0)
891 ++p; /* It was not a class name */
892 }
893 else
894 ++p;
895 }
896
897 return p;
898}
899
900/*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 * Skip past regular expression.
Bram Moolenaar748bf032005-02-02 23:04:36 +0000902 * Stop at end of "startp" or where "dirc" is found ('/', '?', etc).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903 * Take care of characters with a backslash in front of it.
904 * Skip strings inside [ and ].
905 * When "newp" is not NULL and "dirc" is '?', make an allocated copy of the
906 * expression and change "\?" to "?". If "*newp" is not NULL the expression
907 * is changed in-place.
908 */
909 char_u *
910skip_regexp(startp, dirc, magic, newp)
911 char_u *startp;
912 int dirc;
913 int magic;
914 char_u **newp;
915{
916 int mymagic;
917 char_u *p = startp;
918
919 if (magic)
920 mymagic = MAGIC_ON;
921 else
922 mymagic = MAGIC_OFF;
923
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000924 for (; p[0] != NUL; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925 {
926 if (p[0] == dirc) /* found end of regexp */
927 break;
928 if ((p[0] == '[' && mymagic >= MAGIC_ON)
929 || (p[0] == '\\' && p[1] == '[' && mymagic <= MAGIC_OFF))
930 {
931 p = skip_anyof(p + 1);
932 if (p[0] == NUL)
933 break;
934 }
935 else if (p[0] == '\\' && p[1] != NUL)
936 {
937 if (dirc == '?' && newp != NULL && p[1] == '?')
938 {
939 /* change "\?" to "?", make a copy first. */
940 if (*newp == NULL)
941 {
942 *newp = vim_strsave(startp);
943 if (*newp != NULL)
944 p = *newp + (p - startp);
945 }
946 if (*newp != NULL)
947 mch_memmove(p, p + 1, STRLEN(p));
948 else
949 ++p;
950 }
951 else
952 ++p; /* skip next character */
953 if (*p == 'v')
954 mymagic = MAGIC_ALL;
955 else if (*p == 'V')
956 mymagic = MAGIC_NONE;
957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 }
959 return p;
960}
961
962/*
Bram Moolenaar86b68352004-12-27 21:59:20 +0000963 * vim_regcomp() - compile a regular expression into internal code
964 * Returns the program in allocated space. Returns NULL for an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 *
966 * We can't allocate space until we know how big the compiled form will be,
967 * but we can't compile it (and thus know how big it is) until we've got a
968 * place to put the code. So we cheat: we compile it twice, once with code
969 * generation turned off and size counting turned on, and once "for real".
970 * This also means that we don't allocate space until we are sure that the
971 * thing really will compile successfully, and we never have to move the
972 * code and thus invalidate pointers into it. (Note that it has to be in
973 * one piece because vim_free() must be able to free it all.)
974 *
975 * Whether upper/lower case is to be ignored is decided when executing the
976 * program, it does not matter here.
977 *
978 * Beware that the optimization-preparation code in here knows about some
979 * of the structure of the compiled regexp.
980 * "re_flags": RE_MAGIC and/or RE_STRING.
981 */
982 regprog_T *
983vim_regcomp(expr, re_flags)
984 char_u *expr;
985 int re_flags;
986{
987 regprog_T *r;
988 char_u *scan;
989 char_u *longest;
990 int len;
991 int flags;
992
993 if (expr == NULL)
994 EMSG_RET_NULL(_(e_null));
995
996 init_class_tab();
997
998 /*
999 * First pass: determine size, legality.
1000 */
1001 regcomp_start(expr, re_flags);
1002 regcode = JUST_CALC_SIZE;
1003 regc(REGMAGIC);
1004 if (reg(REG_NOPAREN, &flags) == NULL)
1005 return NULL;
1006
1007 /* Small enough for pointer-storage convention? */
1008#ifdef SMALL_MALLOC /* 16 bit storage allocation */
1009 if (regsize >= 65536L - 256L)
1010 EMSG_RET_NULL(_("E339: Pattern too long"));
1011#endif
1012
1013 /* Allocate space. */
1014 r = (regprog_T *)lalloc(sizeof(regprog_T) + regsize, TRUE);
1015 if (r == NULL)
1016 return NULL;
1017
1018 /*
1019 * Second pass: emit code.
1020 */
1021 regcomp_start(expr, re_flags);
1022 regcode = r->program;
1023 regc(REGMAGIC);
1024 if (reg(REG_NOPAREN, &flags) == NULL)
1025 {
1026 vim_free(r);
1027 return NULL;
1028 }
1029
1030 /* Dig out information for optimizations. */
1031 r->regstart = NUL; /* Worst-case defaults. */
1032 r->reganch = 0;
1033 r->regmust = NULL;
1034 r->regmlen = 0;
1035 r->regflags = regflags;
1036 if (flags & HASNL)
1037 r->regflags |= RF_HASNL;
1038 if (flags & HASLOOKBH)
1039 r->regflags |= RF_LOOKBH;
1040#ifdef FEAT_SYN_HL
1041 /* Remember whether this pattern has any \z specials in it. */
1042 r->reghasz = re_has_z;
1043#endif
1044 scan = r->program + 1; /* First BRANCH. */
1045 if (OP(regnext(scan)) == END) /* Only one top-level choice. */
1046 {
1047 scan = OPERAND(scan);
1048
1049 /* Starting-point info. */
1050 if (OP(scan) == BOL || OP(scan) == RE_BOF)
1051 {
1052 r->reganch++;
1053 scan = regnext(scan);
1054 }
1055
1056 if (OP(scan) == EXACTLY)
1057 {
1058#ifdef FEAT_MBYTE
1059 if (has_mbyte)
1060 r->regstart = (*mb_ptr2char)(OPERAND(scan));
1061 else
1062#endif
1063 r->regstart = *OPERAND(scan);
1064 }
1065 else if ((OP(scan) == BOW
1066 || OP(scan) == EOW
1067 || OP(scan) == NOTHING
1068 || OP(scan) == MOPEN + 0 || OP(scan) == NOPEN
1069 || OP(scan) == MCLOSE + 0 || OP(scan) == NCLOSE)
1070 && OP(regnext(scan)) == EXACTLY)
1071 {
1072#ifdef FEAT_MBYTE
1073 if (has_mbyte)
1074 r->regstart = (*mb_ptr2char)(OPERAND(regnext(scan)));
1075 else
1076#endif
1077 r->regstart = *OPERAND(regnext(scan));
1078 }
1079
1080 /*
1081 * If there's something expensive in the r.e., find the longest
1082 * literal string that must appear and make it the regmust. Resolve
1083 * ties in favor of later strings, since the regstart check works
1084 * with the beginning of the r.e. and avoiding duplication
1085 * strengthens checking. Not a strong reason, but sufficient in the
1086 * absence of others.
1087 */
1088 /*
1089 * When the r.e. starts with BOW, it is faster to look for a regmust
1090 * first. Used a lot for "#" and "*" commands. (Added by mool).
1091 */
1092 if ((flags & SPSTART || OP(scan) == BOW || OP(scan) == EOW)
1093 && !(flags & HASNL))
1094 {
1095 longest = NULL;
1096 len = 0;
1097 for (; scan != NULL; scan = regnext(scan))
1098 if (OP(scan) == EXACTLY && STRLEN(OPERAND(scan)) >= (size_t)len)
1099 {
1100 longest = OPERAND(scan);
1101 len = (int)STRLEN(OPERAND(scan));
1102 }
1103 r->regmust = longest;
1104 r->regmlen = len;
1105 }
1106 }
1107#ifdef DEBUG
1108 regdump(expr, r);
1109#endif
1110 return r;
1111}
1112
1113/*
1114 * Setup to parse the regexp. Used once to get the length and once to do it.
1115 */
1116 static void
1117regcomp_start(expr, re_flags)
1118 char_u *expr;
1119 int re_flags; /* see vim_regcomp() */
1120{
1121 initchr(expr);
1122 if (re_flags & RE_MAGIC)
1123 reg_magic = MAGIC_ON;
1124 else
1125 reg_magic = MAGIC_OFF;
1126 reg_string = (re_flags & RE_STRING);
1127
1128 num_complex_braces = 0;
1129 regnpar = 1;
1130 vim_memset(had_endbrace, 0, sizeof(had_endbrace));
1131#ifdef FEAT_SYN_HL
1132 regnzpar = 1;
1133 re_has_z = 0;
1134#endif
1135 regsize = 0L;
1136 regflags = 0;
1137#if defined(FEAT_SYN_HL) || defined(PROTO)
1138 had_eol = FALSE;
1139#endif
1140}
1141
1142#if defined(FEAT_SYN_HL) || defined(PROTO)
1143/*
1144 * Check if during the previous call to vim_regcomp the EOL item "$" has been
1145 * found. This is messy, but it works fine.
1146 */
1147 int
1148vim_regcomp_had_eol()
1149{
1150 return had_eol;
1151}
1152#endif
1153
1154/*
1155 * reg - regular expression, i.e. main body or parenthesized thing
1156 *
1157 * Caller must absorb opening parenthesis.
1158 *
1159 * Combining parenthesis handling with the base level of regular expression
1160 * is a trifle forced, but the need to tie the tails of the branches to what
1161 * follows makes it hard to avoid.
1162 */
1163 static char_u *
1164reg(paren, flagp)
1165 int paren; /* REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN */
1166 int *flagp;
1167{
1168 char_u *ret;
1169 char_u *br;
1170 char_u *ender;
1171 int parno = 0;
1172 int flags;
1173
1174 *flagp = HASWIDTH; /* Tentatively. */
1175
1176#ifdef FEAT_SYN_HL
1177 if (paren == REG_ZPAREN)
1178 {
1179 /* Make a ZOPEN node. */
1180 if (regnzpar >= NSUBEXP)
1181 EMSG_RET_NULL(_("E50: Too many \\z("));
1182 parno = regnzpar;
1183 regnzpar++;
1184 ret = regnode(ZOPEN + parno);
1185 }
1186 else
1187#endif
1188 if (paren == REG_PAREN)
1189 {
1190 /* Make a MOPEN node. */
1191 if (regnpar >= NSUBEXP)
1192 EMSG_M_RET_NULL(_("E51: Too many %s("), reg_magic == MAGIC_ALL);
1193 parno = regnpar;
1194 ++regnpar;
1195 ret = regnode(MOPEN + parno);
1196 }
1197 else if (paren == REG_NPAREN)
1198 {
1199 /* Make a NOPEN node. */
1200 ret = regnode(NOPEN);
1201 }
1202 else
1203 ret = NULL;
1204
1205 /* Pick up the branches, linking them together. */
1206 br = regbranch(&flags);
1207 if (br == NULL)
1208 return NULL;
1209 if (ret != NULL)
1210 regtail(ret, br); /* [MZ]OPEN -> first. */
1211 else
1212 ret = br;
1213 /* If one of the branches can be zero-width, the whole thing can.
1214 * If one of the branches has * at start or matches a line-break, the
1215 * whole thing can. */
1216 if (!(flags & HASWIDTH))
1217 *flagp &= ~HASWIDTH;
1218 *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
1219 while (peekchr() == Magic('|'))
1220 {
1221 skipchr();
1222 br = regbranch(&flags);
1223 if (br == NULL)
1224 return NULL;
1225 regtail(ret, br); /* BRANCH -> BRANCH. */
1226 if (!(flags & HASWIDTH))
1227 *flagp &= ~HASWIDTH;
1228 *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
1229 }
1230
1231 /* Make a closing node, and hook it on the end. */
1232 ender = regnode(
1233#ifdef FEAT_SYN_HL
1234 paren == REG_ZPAREN ? ZCLOSE + parno :
1235#endif
1236 paren == REG_PAREN ? MCLOSE + parno :
1237 paren == REG_NPAREN ? NCLOSE : END);
1238 regtail(ret, ender);
1239
1240 /* Hook the tails of the branches to the closing node. */
1241 for (br = ret; br != NULL; br = regnext(br))
1242 regoptail(br, ender);
1243
1244 /* Check for proper termination. */
1245 if (paren != REG_NOPAREN && getchr() != Magic(')'))
1246 {
1247#ifdef FEAT_SYN_HL
1248 if (paren == REG_ZPAREN)
1249 EMSG_RET_NULL(_("E52: Unmatched \\z("))
1250 else
1251#endif
1252 if (paren == REG_NPAREN)
1253 EMSG_M_RET_NULL(_("E53: Unmatched %s%%("), reg_magic == MAGIC_ALL)
1254 else
1255 EMSG_M_RET_NULL(_("E54: Unmatched %s("), reg_magic == MAGIC_ALL)
1256 }
1257 else if (paren == REG_NOPAREN && peekchr() != NUL)
1258 {
1259 if (curchr == Magic(')'))
1260 EMSG_M_RET_NULL(_("E55: Unmatched %s)"), reg_magic == MAGIC_ALL)
1261 else
1262 EMSG_RET_NULL(_(e_trailing)) /* "Can't happen". */
1263 /* NOTREACHED */
1264 }
1265 /*
1266 * Here we set the flag allowing back references to this set of
1267 * parentheses.
1268 */
1269 if (paren == REG_PAREN)
1270 had_endbrace[parno] = TRUE; /* have seen the close paren */
1271 return ret;
1272}
1273
1274/*
1275 * regbranch - one alternative of an | operator
1276 *
1277 * Implements the & operator.
1278 */
1279 static char_u *
1280regbranch(flagp)
1281 int *flagp;
1282{
1283 char_u *ret;
1284 char_u *chain = NULL;
1285 char_u *latest;
1286 int flags;
1287
1288 *flagp = WORST | HASNL; /* Tentatively. */
1289
1290 ret = regnode(BRANCH);
1291 for (;;)
1292 {
1293 latest = regconcat(&flags);
1294 if (latest == NULL)
1295 return NULL;
1296 /* If one of the branches has width, the whole thing has. If one of
1297 * the branches anchors at start-of-line, the whole thing does.
1298 * If one of the branches uses look-behind, the whole thing does. */
1299 *flagp |= flags & (HASWIDTH | SPSTART | HASLOOKBH);
1300 /* If one of the branches doesn't match a line-break, the whole thing
1301 * doesn't. */
1302 *flagp &= ~HASNL | (flags & HASNL);
1303 if (chain != NULL)
1304 regtail(chain, latest);
1305 if (peekchr() != Magic('&'))
1306 break;
1307 skipchr();
1308 regtail(latest, regnode(END)); /* operand ends */
1309 reginsert(MATCH, latest);
1310 chain = latest;
1311 }
1312
1313 return ret;
1314}
1315
1316/*
1317 * regbranch - one alternative of an | or & operator
1318 *
1319 * Implements the concatenation operator.
1320 */
1321 static char_u *
1322regconcat(flagp)
1323 int *flagp;
1324{
1325 char_u *first = NULL;
1326 char_u *chain = NULL;
1327 char_u *latest;
1328 int flags;
1329 int cont = TRUE;
1330
1331 *flagp = WORST; /* Tentatively. */
1332
1333 while (cont)
1334 {
1335 switch (peekchr())
1336 {
1337 case NUL:
1338 case Magic('|'):
1339 case Magic('&'):
1340 case Magic(')'):
1341 cont = FALSE;
1342 break;
1343 case Magic('Z'):
1344#ifdef FEAT_MBYTE
1345 regflags |= RF_ICOMBINE;
1346#endif
1347 skipchr_keepstart();
1348 break;
1349 case Magic('c'):
1350 regflags |= RF_ICASE;
1351 skipchr_keepstart();
1352 break;
1353 case Magic('C'):
1354 regflags |= RF_NOICASE;
1355 skipchr_keepstart();
1356 break;
1357 case Magic('v'):
1358 reg_magic = MAGIC_ALL;
1359 skipchr_keepstart();
1360 curchr = -1;
1361 break;
1362 case Magic('m'):
1363 reg_magic = MAGIC_ON;
1364 skipchr_keepstart();
1365 curchr = -1;
1366 break;
1367 case Magic('M'):
1368 reg_magic = MAGIC_OFF;
1369 skipchr_keepstart();
1370 curchr = -1;
1371 break;
1372 case Magic('V'):
1373 reg_magic = MAGIC_NONE;
1374 skipchr_keepstart();
1375 curchr = -1;
1376 break;
1377 default:
1378 latest = regpiece(&flags);
1379 if (latest == NULL)
1380 return NULL;
1381 *flagp |= flags & (HASWIDTH | HASNL | HASLOOKBH);
1382 if (chain == NULL) /* First piece. */
1383 *flagp |= flags & SPSTART;
1384 else
1385 regtail(chain, latest);
1386 chain = latest;
1387 if (first == NULL)
1388 first = latest;
1389 break;
1390 }
1391 }
1392 if (first == NULL) /* Loop ran zero times. */
1393 first = regnode(NOTHING);
1394 return first;
1395}
1396
1397/*
1398 * regpiece - something followed by possible [*+=]
1399 *
1400 * Note that the branching code sequences used for = and the general cases
1401 * of * and + are somewhat optimized: they use the same NOTHING node as
1402 * both the endmarker for their branch list and the body of the last branch.
1403 * It might seem that this node could be dispensed with entirely, but the
1404 * endmarker role is not redundant.
1405 */
1406 static char_u *
1407regpiece(flagp)
1408 int *flagp;
1409{
1410 char_u *ret;
1411 int op;
1412 char_u *next;
1413 int flags;
1414 long minval;
1415 long maxval;
1416
1417 ret = regatom(&flags);
1418 if (ret == NULL)
1419 return NULL;
1420
1421 op = peekchr();
1422 if (re_multi_type(op) == NOT_MULTI)
1423 {
1424 *flagp = flags;
1425 return ret;
1426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 /* default flags */
1428 *flagp = (WORST | SPSTART | (flags & (HASNL | HASLOOKBH)));
1429
1430 skipchr();
1431 switch (op)
1432 {
1433 case Magic('*'):
1434 if (flags & SIMPLE)
1435 reginsert(STAR, ret);
1436 else
1437 {
1438 /* Emit x* as (x&|), where & means "self". */
1439 reginsert(BRANCH, ret); /* Either x */
1440 regoptail(ret, regnode(BACK)); /* and loop */
1441 regoptail(ret, ret); /* back */
1442 regtail(ret, regnode(BRANCH)); /* or */
1443 regtail(ret, regnode(NOTHING)); /* null. */
1444 }
1445 break;
1446
1447 case Magic('+'):
1448 if (flags & SIMPLE)
1449 reginsert(PLUS, ret);
1450 else
1451 {
1452 /* Emit x+ as x(&|), where & means "self". */
1453 next = regnode(BRANCH); /* Either */
1454 regtail(ret, next);
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001455 regtail(regnode(BACKP), ret); /* loop back */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 regtail(next, regnode(BRANCH)); /* or */
1457 regtail(ret, regnode(NOTHING)); /* null. */
1458 }
1459 *flagp = (WORST | HASWIDTH | (flags & (HASNL | HASLOOKBH)));
1460 break;
1461
1462 case Magic('@'):
1463 {
1464 int lop = END;
1465
1466 switch (no_Magic(getchr()))
1467 {
1468 case '=': lop = MATCH; break; /* \@= */
1469 case '!': lop = NOMATCH; break; /* \@! */
1470 case '>': lop = SUBPAT; break; /* \@> */
1471 case '<': switch (no_Magic(getchr()))
1472 {
1473 case '=': lop = BEHIND; break; /* \@<= */
1474 case '!': lop = NOBEHIND; break; /* \@<! */
1475 }
1476 }
1477 if (lop == END)
1478 EMSG_M_RET_NULL(_("E59: invalid character after %s@"),
1479 reg_magic == MAGIC_ALL);
1480 /* Look behind must match with behind_pos. */
1481 if (lop == BEHIND || lop == NOBEHIND)
1482 {
1483 regtail(ret, regnode(BHPOS));
1484 *flagp |= HASLOOKBH;
1485 }
1486 regtail(ret, regnode(END)); /* operand ends */
1487 reginsert(lop, ret);
1488 break;
1489 }
1490
1491 case Magic('?'):
1492 case Magic('='):
1493 /* Emit x= as (x|) */
1494 reginsert(BRANCH, ret); /* Either x */
1495 regtail(ret, regnode(BRANCH)); /* or */
1496 next = regnode(NOTHING); /* null. */
1497 regtail(ret, next);
1498 regoptail(ret, next);
1499 break;
1500
1501 case Magic('{'):
1502 if (!read_limits(&minval, &maxval))
1503 return NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 if (flags & SIMPLE)
1505 {
1506 reginsert(BRACE_SIMPLE, ret);
1507 reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
1508 }
1509 else
1510 {
1511 if (num_complex_braces >= 10)
1512 EMSG_M_RET_NULL(_("E60: Too many complex %s{...}s"),
1513 reg_magic == MAGIC_ALL);
1514 reginsert(BRACE_COMPLEX + num_complex_braces, ret);
1515 regoptail(ret, regnode(BACK));
1516 regoptail(ret, ret);
1517 reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
1518 ++num_complex_braces;
1519 }
1520 if (minval > 0 && maxval > 0)
1521 *flagp = (HASWIDTH | (flags & (HASNL | HASLOOKBH)));
1522 break;
1523 }
1524 if (re_multi_type(peekchr()) != NOT_MULTI)
1525 {
1526 /* Can't have a multi follow a multi. */
1527 if (peekchr() == Magic('*'))
1528 sprintf((char *)IObuff, _("E61: Nested %s*"),
1529 reg_magic >= MAGIC_ON ? "" : "\\");
1530 else
1531 sprintf((char *)IObuff, _("E62: Nested %s%c"),
1532 reg_magic == MAGIC_ALL ? "" : "\\", no_Magic(peekchr()));
1533 EMSG_RET_NULL(IObuff);
1534 }
1535
1536 return ret;
1537}
1538
1539/*
1540 * regatom - the lowest level
1541 *
1542 * Optimization: gobbles an entire sequence of ordinary characters so that
1543 * it can turn them into a single node, which is smaller to store and
1544 * faster to run. Don't do this when one_exactly is set.
1545 */
1546 static char_u *
1547regatom(flagp)
1548 int *flagp;
1549{
1550 char_u *ret;
1551 int flags;
1552 int cpo_lit; /* 'cpoptions' contains 'l' flag */
Bram Moolenaardf177f62005-02-22 08:39:57 +00001553 int cpo_bsl; /* 'cpoptions' contains '\' flag */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 int c;
1555 static char_u *classchars = (char_u *)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
1556 static int classcodes[] = {ANY, IDENT, SIDENT, KWORD, SKWORD,
1557 FNAME, SFNAME, PRINT, SPRINT,
1558 WHITE, NWHITE, DIGIT, NDIGIT,
1559 HEX, NHEX, OCTAL, NOCTAL,
1560 WORD, NWORD, HEAD, NHEAD,
1561 ALPHA, NALPHA, LOWER, NLOWER,
1562 UPPER, NUPPER
1563 };
1564 char_u *p;
1565 int extra = 0;
1566
1567 *flagp = WORST; /* Tentatively. */
1568 cpo_lit = (!reg_syn && vim_strchr(p_cpo, CPO_LITERAL) != NULL);
Bram Moolenaardf177f62005-02-22 08:39:57 +00001569 cpo_bsl = (!reg_syn && vim_strchr(p_cpo, CPO_BACKSL) != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570
1571 c = getchr();
1572 switch (c)
1573 {
1574 case Magic('^'):
1575 ret = regnode(BOL);
1576 break;
1577
1578 case Magic('$'):
1579 ret = regnode(EOL);
1580#if defined(FEAT_SYN_HL) || defined(PROTO)
1581 had_eol = TRUE;
1582#endif
1583 break;
1584
1585 case Magic('<'):
1586 ret = regnode(BOW);
1587 break;
1588
1589 case Magic('>'):
1590 ret = regnode(EOW);
1591 break;
1592
1593 case Magic('_'):
1594 c = no_Magic(getchr());
1595 if (c == '^') /* "\_^" is start-of-line */
1596 {
1597 ret = regnode(BOL);
1598 break;
1599 }
1600 if (c == '$') /* "\_$" is end-of-line */
1601 {
1602 ret = regnode(EOL);
1603#if defined(FEAT_SYN_HL) || defined(PROTO)
1604 had_eol = TRUE;
1605#endif
1606 break;
1607 }
1608
1609 extra = ADD_NL;
1610 *flagp |= HASNL;
1611
1612 /* "\_[" is character range plus newline */
1613 if (c == '[')
1614 goto collection;
1615
1616 /* "\_x" is character class plus newline */
1617 /*FALLTHROUGH*/
1618
1619 /*
1620 * Character classes.
1621 */
1622 case Magic('.'):
1623 case Magic('i'):
1624 case Magic('I'):
1625 case Magic('k'):
1626 case Magic('K'):
1627 case Magic('f'):
1628 case Magic('F'):
1629 case Magic('p'):
1630 case Magic('P'):
1631 case Magic('s'):
1632 case Magic('S'):
1633 case Magic('d'):
1634 case Magic('D'):
1635 case Magic('x'):
1636 case Magic('X'):
1637 case Magic('o'):
1638 case Magic('O'):
1639 case Magic('w'):
1640 case Magic('W'):
1641 case Magic('h'):
1642 case Magic('H'):
1643 case Magic('a'):
1644 case Magic('A'):
1645 case Magic('l'):
1646 case Magic('L'):
1647 case Magic('u'):
1648 case Magic('U'):
1649 p = vim_strchr(classchars, no_Magic(c));
1650 if (p == NULL)
1651 EMSG_RET_NULL(_("E63: invalid use of \\_"));
1652 ret = regnode(classcodes[p - classchars] + extra);
1653 *flagp |= HASWIDTH | SIMPLE;
1654 break;
1655
1656 case Magic('n'):
1657 if (reg_string)
1658 {
1659 /* In a string "\n" matches a newline character. */
1660 ret = regnode(EXACTLY);
1661 regc(NL);
1662 regc(NUL);
1663 *flagp |= HASWIDTH | SIMPLE;
1664 }
1665 else
1666 {
1667 /* In buffer text "\n" matches the end of a line. */
1668 ret = regnode(NEWL);
1669 *flagp |= HASWIDTH | HASNL;
1670 }
1671 break;
1672
1673 case Magic('('):
1674 if (one_exactly)
1675 EMSG_ONE_RET_NULL;
1676 ret = reg(REG_PAREN, &flags);
1677 if (ret == NULL)
1678 return NULL;
1679 *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
1680 break;
1681
1682 case NUL:
1683 case Magic('|'):
1684 case Magic('&'):
1685 case Magic(')'):
1686 EMSG_RET_NULL(_(e_internal)); /* Supposed to be caught earlier. */
1687 /* NOTREACHED */
1688
1689 case Magic('='):
1690 case Magic('?'):
1691 case Magic('+'):
1692 case Magic('@'):
1693 case Magic('{'):
1694 case Magic('*'):
1695 c = no_Magic(c);
1696 sprintf((char *)IObuff, _("E64: %s%c follows nothing"),
1697 (c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL)
1698 ? "" : "\\", c);
1699 EMSG_RET_NULL(IObuff);
1700 /* NOTREACHED */
1701
1702 case Magic('~'): /* previous substitute pattern */
1703 if (reg_prev_sub)
1704 {
1705 char_u *lp;
1706
1707 ret = regnode(EXACTLY);
1708 lp = reg_prev_sub;
1709 while (*lp != NUL)
1710 regc(*lp++);
1711 regc(NUL);
1712 if (*reg_prev_sub != NUL)
1713 {
1714 *flagp |= HASWIDTH;
1715 if ((lp - reg_prev_sub) == 1)
1716 *flagp |= SIMPLE;
1717 }
1718 }
1719 else
1720 EMSG_RET_NULL(_(e_nopresub));
1721 break;
1722
1723 case Magic('1'):
1724 case Magic('2'):
1725 case Magic('3'):
1726 case Magic('4'):
1727 case Magic('5'):
1728 case Magic('6'):
1729 case Magic('7'):
1730 case Magic('8'):
1731 case Magic('9'):
1732 {
1733 int refnum;
1734
1735 refnum = c - Magic('0');
1736 /*
1737 * Check if the back reference is legal. We must have seen the
1738 * close brace.
1739 * TODO: Should also check that we don't refer to something
1740 * that is repeated (+*=): what instance of the repetition
1741 * should we match?
1742 */
1743 if (!had_endbrace[refnum])
1744 {
1745 /* Trick: check if "@<=" or "@<!" follows, in which case
1746 * the \1 can appear before the referenced match. */
1747 for (p = regparse; *p != NUL; ++p)
1748 if (p[0] == '@' && p[1] == '<'
1749 && (p[2] == '!' || p[2] == '='))
1750 break;
1751 if (*p == NUL)
1752 EMSG_RET_NULL(_("E65: Illegal back reference"));
1753 }
1754 ret = regnode(BACKREF + refnum);
1755 }
1756 break;
1757
1758#ifdef FEAT_SYN_HL
1759 case Magic('z'):
1760 {
1761 c = no_Magic(getchr());
1762 switch (c)
1763 {
1764 case '(': if (reg_do_extmatch != REX_SET)
1765 EMSG_RET_NULL(_("E66: \\z( not allowed here"));
1766 if (one_exactly)
1767 EMSG_ONE_RET_NULL;
1768 ret = reg(REG_ZPAREN, &flags);
1769 if (ret == NULL)
1770 return NULL;
1771 *flagp |= flags & (HASWIDTH|SPSTART|HASNL|HASLOOKBH);
1772 re_has_z = REX_SET;
1773 break;
1774
1775 case '1':
1776 case '2':
1777 case '3':
1778 case '4':
1779 case '5':
1780 case '6':
1781 case '7':
1782 case '8':
1783 case '9': if (reg_do_extmatch != REX_USE)
1784 EMSG_RET_NULL(_("E67: \\z1 et al. not allowed here"));
1785 ret = regnode(ZREF + c - '0');
1786 re_has_z = REX_USE;
1787 break;
1788
1789 case 's': ret = regnode(MOPEN + 0);
1790 break;
1791
1792 case 'e': ret = regnode(MCLOSE + 0);
1793 break;
1794
1795 default: EMSG_RET_NULL(_("E68: Invalid character after \\z"));
1796 }
1797 }
1798 break;
1799#endif
1800
1801 case Magic('%'):
1802 {
1803 c = no_Magic(getchr());
1804 switch (c)
1805 {
1806 /* () without a back reference */
1807 case '(':
1808 if (one_exactly)
1809 EMSG_ONE_RET_NULL;
1810 ret = reg(REG_NPAREN, &flags);
1811 if (ret == NULL)
1812 return NULL;
1813 *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
1814 break;
1815
1816 /* Catch \%^ and \%$ regardless of where they appear in the
1817 * pattern -- regardless of whether or not it makes sense. */
1818 case '^':
1819 ret = regnode(RE_BOF);
1820 break;
1821
1822 case '$':
1823 ret = regnode(RE_EOF);
1824 break;
1825
1826 case '#':
1827 ret = regnode(CURSOR);
1828 break;
1829
1830 /* \%[abc]: Emit as a list of branches, all ending at the last
1831 * branch which matches nothing. */
1832 case '[':
1833 if (one_exactly) /* doesn't nest */
1834 EMSG_ONE_RET_NULL;
1835 {
1836 char_u *lastbranch;
1837 char_u *lastnode = NULL;
1838 char_u *br;
1839
1840 ret = NULL;
1841 while ((c = getchr()) != ']')
1842 {
1843 if (c == NUL)
1844 EMSG_M_RET_NULL(_("E69: Missing ] after %s%%["),
1845 reg_magic == MAGIC_ALL);
1846 br = regnode(BRANCH);
1847 if (ret == NULL)
1848 ret = br;
1849 else
1850 regtail(lastnode, br);
1851
1852 ungetchr();
1853 one_exactly = TRUE;
1854 lastnode = regatom(flagp);
1855 one_exactly = FALSE;
1856 if (lastnode == NULL)
1857 return NULL;
1858 }
1859 if (ret == NULL)
1860 EMSG_M_RET_NULL(_("E70: Empty %s%%[]"),
1861 reg_magic == MAGIC_ALL);
1862 lastbranch = regnode(BRANCH);
1863 br = regnode(NOTHING);
1864 if (ret != JUST_CALC_SIZE)
1865 {
1866 regtail(lastnode, br);
1867 regtail(lastbranch, br);
1868 /* connect all branches to the NOTHING
1869 * branch at the end */
1870 for (br = ret; br != lastnode; )
1871 {
1872 if (OP(br) == BRANCH)
1873 {
1874 regtail(br, lastbranch);
1875 br = OPERAND(br);
1876 }
1877 else
1878 br = regnext(br);
1879 }
1880 }
1881 *flagp &= ~HASWIDTH;
1882 break;
1883 }
1884
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001885 case 'd': /* %d123 decimal */
1886 case 'o': /* %o123 octal */
1887 case 'x': /* %xab hex 2 */
1888 case 'u': /* %uabcd hex 4 */
1889 case 'U': /* %U1234abcd hex 8 */
1890 {
1891 int i;
1892
1893 switch (c)
1894 {
1895 case 'd': i = getdecchrs(); break;
1896 case 'o': i = getoctchrs(); break;
1897 case 'x': i = gethexchrs(2); break;
1898 case 'u': i = gethexchrs(4); break;
1899 case 'U': i = gethexchrs(8); break;
1900 default: i = -1; break;
1901 }
1902
1903 if (i < 0)
1904 EMSG_M_RET_NULL(
1905 _("E678: Invalid character after %s%%[dxouU]"),
1906 reg_magic == MAGIC_ALL);
1907 ret = regnode(EXACTLY);
1908 if (i == 0)
1909 regc(0x0a);
1910 else
1911#ifdef FEAT_MBYTE
1912 regmbc(i);
1913#else
1914 regc(i);
1915#endif
1916 regc(NUL);
1917 *flagp |= HASWIDTH;
1918 break;
1919 }
1920
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 default:
1922 if (VIM_ISDIGIT(c) || c == '<' || c == '>')
1923 {
1924 long_u n = 0;
1925 int cmp;
1926
1927 cmp = c;
1928 if (cmp == '<' || cmp == '>')
1929 c = getchr();
1930 while (VIM_ISDIGIT(c))
1931 {
1932 n = n * 10 + (c - '0');
1933 c = getchr();
1934 }
1935 if (c == 'l' || c == 'c' || c == 'v')
1936 {
1937 if (c == 'l')
1938 ret = regnode(RE_LNUM);
1939 else if (c == 'c')
1940 ret = regnode(RE_COL);
1941 else
1942 ret = regnode(RE_VCOL);
1943 if (ret == JUST_CALC_SIZE)
1944 regsize += 5;
1945 else
1946 {
1947 /* put the number and the optional
1948 * comparator after the opcode */
1949 regcode = re_put_long(regcode, n);
1950 *regcode++ = cmp;
1951 }
1952 break;
1953 }
1954 }
1955
1956 EMSG_M_RET_NULL(_("E71: Invalid character after %s%%"),
1957 reg_magic == MAGIC_ALL);
1958 }
1959 }
1960 break;
1961
1962 case Magic('['):
1963collection:
1964 {
1965 char_u *lp;
1966
1967 /*
1968 * If there is no matching ']', we assume the '[' is a normal
1969 * character. This makes 'incsearch' and ":help [" work.
1970 */
1971 lp = skip_anyof(regparse);
1972 if (*lp == ']') /* there is a matching ']' */
1973 {
1974 int startc = -1; /* > 0 when next '-' is a range */
1975 int endc;
1976
1977 /*
1978 * In a character class, different parsing rules apply.
1979 * Not even \ is special anymore, nothing is.
1980 */
1981 if (*regparse == '^') /* Complement of range. */
1982 {
1983 ret = regnode(ANYBUT + extra);
1984 regparse++;
1985 }
1986 else
1987 ret = regnode(ANYOF + extra);
1988
1989 /* At the start ']' and '-' mean the literal character. */
1990 if (*regparse == ']' || *regparse == '-')
Bram Moolenaardf177f62005-02-22 08:39:57 +00001991 {
1992 startc = *regparse;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 regc(*regparse++);
Bram Moolenaardf177f62005-02-22 08:39:57 +00001994 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995
1996 while (*regparse != NUL && *regparse != ']')
1997 {
1998 if (*regparse == '-')
1999 {
2000 ++regparse;
2001 /* The '-' is not used for a range at the end and
2002 * after or before a '\n'. */
2003 if (*regparse == ']' || *regparse == NUL
2004 || startc == -1
2005 || (regparse[0] == '\\' && regparse[1] == 'n'))
2006 {
2007 regc('-');
2008 startc = '-'; /* [--x] is a range */
2009 }
2010 else
2011 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00002012 /* Also accept "a-[.z.]" */
2013 endc = 0;
2014 if (*regparse == '[')
2015 endc = get_coll_element(&regparse);
2016 if (endc == 0)
2017 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018#ifdef FEAT_MBYTE
Bram Moolenaardf177f62005-02-22 08:39:57 +00002019 if (has_mbyte)
2020 endc = mb_ptr2char_adv(&regparse);
2021 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00002023 endc = *regparse++;
2024 }
Bram Moolenaarc0197e22004-09-13 20:26:32 +00002025
2026 /* Handle \o40, \x20 and \u20AC style sequences */
Bram Moolenaardf177f62005-02-22 08:39:57 +00002027 if (endc == '\\' && !cpo_lit && !cpo_bsl)
Bram Moolenaarc0197e22004-09-13 20:26:32 +00002028 endc = coll_get_char();
2029
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 if (startc > endc)
2031 EMSG_RET_NULL(_(e_invrange));
2032#ifdef FEAT_MBYTE
2033 if (has_mbyte && ((*mb_char2len)(startc) > 1
2034 || (*mb_char2len)(endc) > 1))
2035 {
2036 /* Limit to a range of 256 chars */
2037 if (endc > startc + 256)
2038 EMSG_RET_NULL(_(e_invrange));
2039 while (++startc <= endc)
2040 regmbc(startc);
2041 }
2042 else
2043#endif
2044 {
2045#ifdef EBCDIC
2046 int alpha_only = FALSE;
2047
2048 /* for alphabetical range skip the gaps
2049 * 'i'-'j', 'r'-'s', 'I'-'J' and 'R'-'S'. */
2050 if (isalpha(startc) && isalpha(endc))
2051 alpha_only = TRUE;
2052#endif
2053 while (++startc <= endc)
2054#ifdef EBCDIC
2055 if (!alpha_only || isalpha(startc))
2056#endif
2057 regc(startc);
2058 }
2059 startc = -1;
2060 }
2061 }
2062 /*
2063 * Only "\]", "\^", "\]" and "\\" are special in Vi. Vim
2064 * accepts "\t", "\e", etc., but only when the 'l' flag in
2065 * 'cpoptions' is not included.
Bram Moolenaardf177f62005-02-22 08:39:57 +00002066 * Posix doesn't recognize backslash at all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 */
2068 else if (*regparse == '\\'
Bram Moolenaardf177f62005-02-22 08:39:57 +00002069 && !cpo_bsl
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 && (vim_strchr(REGEXP_INRANGE, regparse[1]) != NULL
2071 || (!cpo_lit
2072 && vim_strchr(REGEXP_ABBR,
2073 regparse[1]) != NULL)))
2074 {
2075 regparse++;
2076 if (*regparse == 'n')
2077 {
2078 /* '\n' in range: also match NL */
2079 if (ret != JUST_CALC_SIZE)
2080 {
2081 if (*ret == ANYBUT)
2082 *ret = ANYBUT + ADD_NL;
2083 else if (*ret == ANYOF)
2084 *ret = ANYOF + ADD_NL;
2085 /* else: must have had a \n already */
2086 }
2087 *flagp |= HASNL;
2088 regparse++;
2089 startc = -1;
2090 }
Bram Moolenaarc0197e22004-09-13 20:26:32 +00002091 else if (*regparse == 'd'
2092 || *regparse == 'o'
2093 || *regparse == 'x'
2094 || *regparse == 'u'
2095 || *regparse == 'U')
2096 {
2097 startc = coll_get_char();
2098 if (startc == 0)
2099 regc(0x0a);
2100 else
2101#ifdef FEAT_MBYTE
2102 regmbc(startc);
2103#else
2104 regc(startc);
2105#endif
2106 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107 else
2108 {
2109 startc = backslash_trans(*regparse++);
2110 regc(startc);
2111 }
2112 }
2113 else if (*regparse == '[')
2114 {
2115 int c_class;
2116 int cu;
2117
Bram Moolenaardf177f62005-02-22 08:39:57 +00002118 c_class = get_char_class(&regparse);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 startc = -1;
2120 /* Characters assumed to be 8 bits! */
2121 switch (c_class)
2122 {
2123 case CLASS_NONE:
Bram Moolenaardf177f62005-02-22 08:39:57 +00002124 c_class = get_equi_class(&regparse);
2125 if (c_class != 0)
2126 {
2127 /* produce equivalence class */
2128 reg_equi_class(c_class);
2129 }
2130 else if ((c_class =
2131 get_coll_element(&regparse)) != 0)
2132 {
2133 /* produce a collating element */
2134 regmbc(c_class);
2135 }
2136 else
2137 {
2138 /* literal '[', allow [[-x] as a range */
2139 startc = *regparse++;
2140 regc(startc);
2141 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 break;
2143 case CLASS_ALNUM:
2144 for (cu = 1; cu <= 255; cu++)
2145 if (isalnum(cu))
2146 regc(cu);
2147 break;
2148 case CLASS_ALPHA:
2149 for (cu = 1; cu <= 255; cu++)
2150 if (isalpha(cu))
2151 regc(cu);
2152 break;
2153 case CLASS_BLANK:
2154 regc(' ');
2155 regc('\t');
2156 break;
2157 case CLASS_CNTRL:
2158 for (cu = 1; cu <= 255; cu++)
2159 if (iscntrl(cu))
2160 regc(cu);
2161 break;
2162 case CLASS_DIGIT:
2163 for (cu = 1; cu <= 255; cu++)
2164 if (VIM_ISDIGIT(cu))
2165 regc(cu);
2166 break;
2167 case CLASS_GRAPH:
2168 for (cu = 1; cu <= 255; cu++)
2169 if (isgraph(cu))
2170 regc(cu);
2171 break;
2172 case CLASS_LOWER:
2173 for (cu = 1; cu <= 255; cu++)
2174 if (islower(cu))
2175 regc(cu);
2176 break;
2177 case CLASS_PRINT:
2178 for (cu = 1; cu <= 255; cu++)
2179 if (vim_isprintc(cu))
2180 regc(cu);
2181 break;
2182 case CLASS_PUNCT:
2183 for (cu = 1; cu <= 255; cu++)
2184 if (ispunct(cu))
2185 regc(cu);
2186 break;
2187 case CLASS_SPACE:
2188 for (cu = 9; cu <= 13; cu++)
2189 regc(cu);
2190 regc(' ');
2191 break;
2192 case CLASS_UPPER:
2193 for (cu = 1; cu <= 255; cu++)
2194 if (isupper(cu))
2195 regc(cu);
2196 break;
2197 case CLASS_XDIGIT:
2198 for (cu = 1; cu <= 255; cu++)
2199 if (vim_isxdigit(cu))
2200 regc(cu);
2201 break;
2202 case CLASS_TAB:
2203 regc('\t');
2204 break;
2205 case CLASS_RETURN:
2206 regc('\r');
2207 break;
2208 case CLASS_BACKSPACE:
2209 regc('\b');
2210 break;
2211 case CLASS_ESCAPE:
2212 regc('\033');
2213 break;
2214 }
2215 }
2216 else
2217 {
2218#ifdef FEAT_MBYTE
2219 if (has_mbyte)
2220 {
2221 int len;
2222
2223 /* produce a multibyte character, including any
2224 * following composing characters */
2225 startc = mb_ptr2char(regparse);
2226 len = (*mb_ptr2len_check)(regparse);
2227 if (enc_utf8 && utf_char2len(startc) != len)
2228 startc = -1; /* composing chars */
2229 while (--len >= 0)
2230 regc(*regparse++);
2231 }
2232 else
2233#endif
2234 {
2235 startc = *regparse++;
2236 regc(startc);
2237 }
2238 }
2239 }
2240 regc(NUL);
2241 prevchr_len = 1; /* last char was the ']' */
2242 if (*regparse != ']')
2243 EMSG_RET_NULL(_(e_toomsbra)); /* Cannot happen? */
2244 skipchr(); /* let's be friends with the lexer again */
2245 *flagp |= HASWIDTH | SIMPLE;
2246 break;
2247 }
2248 }
2249 /* FALLTHROUGH */
2250
2251 default:
2252 {
2253 int len;
2254
2255#ifdef FEAT_MBYTE
2256 /* A multi-byte character is handled as a separate atom if it's
2257 * before a multi. */
2258 if (has_mbyte && (*mb_char2len)(c) > 1
2259 && re_multi_type(peekchr()) != NOT_MULTI)
2260 {
2261 ret = regnode(MULTIBYTECODE);
2262 regmbc(c);
2263 *flagp |= HASWIDTH | SIMPLE;
2264 break;
2265 }
2266#endif
2267
2268 ret = regnode(EXACTLY);
2269
2270 /*
2271 * Append characters as long as:
2272 * - there is no following multi, we then need the character in
2273 * front of it as a single character operand
2274 * - not running into a Magic character
2275 * - "one_exactly" is not set
2276 * But always emit at least one character. Might be a Multi,
2277 * e.g., a "[" without matching "]".
2278 */
2279 for (len = 0; c != NUL && (len == 0
2280 || (re_multi_type(peekchr()) == NOT_MULTI
2281 && !one_exactly
2282 && !is_Magic(c))); ++len)
2283 {
2284 c = no_Magic(c);
2285#ifdef FEAT_MBYTE
2286 if (has_mbyte)
2287 {
2288 regmbc(c);
2289 if (enc_utf8)
2290 {
2291 int off;
2292 int l;
2293
2294 /* Need to get composing character too, directly
2295 * access regparse for that, because skipchr() skips
2296 * over composing chars. */
2297 ungetchr();
2298 if (*regparse == '\\' && regparse[1] != NUL)
2299 off = 1;
2300 else
2301 off = 0;
2302 for (;;)
2303 {
2304 l = utf_ptr2len_check(regparse + off);
2305 if (!UTF_COMPOSINGLIKE(regparse + off,
2306 regparse + off + l))
2307 break;
2308 off += l;
2309 regmbc(utf_ptr2char(regparse + off));
2310 }
2311 skipchr();
2312 }
2313 }
2314 else
2315#endif
2316 regc(c);
2317 c = getchr();
2318 }
2319 ungetchr();
2320
2321 regc(NUL);
2322 *flagp |= HASWIDTH;
2323 if (len == 1)
2324 *flagp |= SIMPLE;
2325 }
2326 break;
2327 }
2328
2329 return ret;
2330}
2331
2332/*
2333 * emit a node
2334 * Return pointer to generated code.
2335 */
2336 static char_u *
2337regnode(op)
2338 int op;
2339{
2340 char_u *ret;
2341
2342 ret = regcode;
2343 if (ret == JUST_CALC_SIZE)
2344 regsize += 3;
2345 else
2346 {
2347 *regcode++ = op;
2348 *regcode++ = NUL; /* Null "next" pointer. */
2349 *regcode++ = NUL;
2350 }
2351 return ret;
2352}
2353
2354/*
2355 * Emit (if appropriate) a byte of code
2356 */
2357 static void
2358regc(b)
2359 int b;
2360{
2361 if (regcode == JUST_CALC_SIZE)
2362 regsize++;
2363 else
2364 *regcode++ = b;
2365}
2366
2367#ifdef FEAT_MBYTE
2368/*
2369 * Emit (if appropriate) a multi-byte character of code
2370 */
2371 static void
2372regmbc(c)
2373 int c;
2374{
2375 if (regcode == JUST_CALC_SIZE)
2376 regsize += (*mb_char2len)(c);
2377 else
2378 regcode += (*mb_char2bytes)(c, regcode);
2379}
2380#endif
2381
2382/*
2383 * reginsert - insert an operator in front of already-emitted operand
2384 *
2385 * Means relocating the operand.
2386 */
2387 static void
2388reginsert(op, opnd)
2389 int op;
2390 char_u *opnd;
2391{
2392 char_u *src;
2393 char_u *dst;
2394 char_u *place;
2395
2396 if (regcode == JUST_CALC_SIZE)
2397 {
2398 regsize += 3;
2399 return;
2400 }
2401 src = regcode;
2402 regcode += 3;
2403 dst = regcode;
2404 while (src > opnd)
2405 *--dst = *--src;
2406
2407 place = opnd; /* Op node, where operand used to be. */
2408 *place++ = op;
2409 *place++ = NUL;
2410 *place = NUL;
2411}
2412
2413/*
2414 * reginsert_limits - insert an operator in front of already-emitted operand.
2415 * The operator has the given limit values as operands. Also set next pointer.
2416 *
2417 * Means relocating the operand.
2418 */
2419 static void
2420reginsert_limits(op, minval, maxval, opnd)
2421 int op;
2422 long minval;
2423 long maxval;
2424 char_u *opnd;
2425{
2426 char_u *src;
2427 char_u *dst;
2428 char_u *place;
2429
2430 if (regcode == JUST_CALC_SIZE)
2431 {
2432 regsize += 11;
2433 return;
2434 }
2435 src = regcode;
2436 regcode += 11;
2437 dst = regcode;
2438 while (src > opnd)
2439 *--dst = *--src;
2440
2441 place = opnd; /* Op node, where operand used to be. */
2442 *place++ = op;
2443 *place++ = NUL;
2444 *place++ = NUL;
2445 place = re_put_long(place, (long_u)minval);
2446 place = re_put_long(place, (long_u)maxval);
2447 regtail(opnd, place);
2448}
2449
2450/*
2451 * Write a long as four bytes at "p" and return pointer to the next char.
2452 */
2453 static char_u *
2454re_put_long(p, val)
2455 char_u *p;
2456 long_u val;
2457{
2458 *p++ = (char_u) ((val >> 24) & 0377);
2459 *p++ = (char_u) ((val >> 16) & 0377);
2460 *p++ = (char_u) ((val >> 8) & 0377);
2461 *p++ = (char_u) (val & 0377);
2462 return p;
2463}
2464
2465/*
2466 * regtail - set the next-pointer at the end of a node chain
2467 */
2468 static void
2469regtail(p, val)
2470 char_u *p;
2471 char_u *val;
2472{
2473 char_u *scan;
2474 char_u *temp;
2475 int offset;
2476
2477 if (p == JUST_CALC_SIZE)
2478 return;
2479
2480 /* Find last node. */
2481 scan = p;
2482 for (;;)
2483 {
2484 temp = regnext(scan);
2485 if (temp == NULL)
2486 break;
2487 scan = temp;
2488 }
2489
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002490 if (OP(scan) == BACK || OP(scan) == BACKP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 offset = (int)(scan - val);
2492 else
2493 offset = (int)(val - scan);
2494 *(scan + 1) = (char_u) (((unsigned)offset >> 8) & 0377);
2495 *(scan + 2) = (char_u) (offset & 0377);
2496}
2497
2498/*
2499 * regoptail - regtail on item after a BRANCH; nop if none
2500 */
2501 static void
2502regoptail(p, val)
2503 char_u *p;
2504 char_u *val;
2505{
2506 /* When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless" */
2507 if (p == NULL || p == JUST_CALC_SIZE
2508 || (OP(p) != BRANCH
2509 && (OP(p) < BRACE_COMPLEX || OP(p) > BRACE_COMPLEX + 9)))
2510 return;
2511 regtail(OPERAND(p), val);
2512}
2513
2514/*
2515 * getchr() - get the next character from the pattern. We know about
2516 * magic and such, so therefore we need a lexical analyzer.
2517 */
2518
2519/* static int curchr; */
2520static int prevprevchr;
2521static int prevchr;
2522static int nextchr; /* used for ungetchr() */
2523/*
2524 * Note: prevchr is sometimes -1 when we are not at the start,
2525 * eg in /[ ^I]^ the pattern was never found even if it existed, because ^ was
2526 * taken to be magic -- webb
2527 */
2528static int at_start; /* True when on the first character */
2529static int prev_at_start; /* True when on the second character */
2530
2531 static void
2532initchr(str)
2533 char_u *str;
2534{
2535 regparse = str;
2536 prevchr_len = 0;
2537 curchr = prevprevchr = prevchr = nextchr = -1;
2538 at_start = TRUE;
2539 prev_at_start = FALSE;
2540}
2541
2542 static int
2543peekchr()
2544{
Bram Moolenaardf177f62005-02-22 08:39:57 +00002545 static int after_slash = FALSE;
2546
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 if (curchr == -1)
2548 {
2549 switch (curchr = regparse[0])
2550 {
2551 case '.':
2552 case '[':
2553 case '~':
2554 /* magic when 'magic' is on */
2555 if (reg_magic >= MAGIC_ON)
2556 curchr = Magic(curchr);
2557 break;
2558 case '(':
2559 case ')':
2560 case '{':
2561 case '%':
2562 case '+':
2563 case '=':
2564 case '?':
2565 case '@':
2566 case '!':
2567 case '&':
2568 case '|':
2569 case '<':
2570 case '>':
2571 case '#': /* future ext. */
2572 case '"': /* future ext. */
2573 case '\'': /* future ext. */
2574 case ',': /* future ext. */
2575 case '-': /* future ext. */
2576 case ':': /* future ext. */
2577 case ';': /* future ext. */
2578 case '`': /* future ext. */
2579 case '/': /* Can't be used in / command */
2580 /* magic only after "\v" */
2581 if (reg_magic == MAGIC_ALL)
2582 curchr = Magic(curchr);
2583 break;
2584 case '*':
Bram Moolenaardf177f62005-02-22 08:39:57 +00002585 /* * is not magic as the very first character, eg "?*ptr", when
2586 * after '^', eg "/^*ptr" and when after "\(", "\|", "\&". But
2587 * "\(\*" is not magic, thus must be magic if "after_slash" */
2588 if (reg_magic >= MAGIC_ON
2589 && !at_start
2590 && !(prev_at_start && prevchr == Magic('^'))
2591 && (after_slash
2592 || (prevchr != Magic('(')
2593 && prevchr != Magic('&')
2594 && prevchr != Magic('|'))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 curchr = Magic('*');
2596 break;
2597 case '^':
2598 /* '^' is only magic as the very first character and if it's after
2599 * "\(", "\|", "\&' or "\n" */
2600 if (reg_magic >= MAGIC_OFF
2601 && (at_start
2602 || reg_magic == MAGIC_ALL
2603 || prevchr == Magic('(')
2604 || prevchr == Magic('|')
2605 || prevchr == Magic('&')
2606 || prevchr == Magic('n')
2607 || (no_Magic(prevchr) == '('
2608 && prevprevchr == Magic('%'))))
2609 {
2610 curchr = Magic('^');
2611 at_start = TRUE;
2612 prev_at_start = FALSE;
2613 }
2614 break;
2615 case '$':
2616 /* '$' is only magic as the very last char and if it's in front of
2617 * either "\|", "\)", "\&", or "\n" */
2618 if (reg_magic >= MAGIC_OFF)
2619 {
2620 char_u *p = regparse + 1;
2621
2622 /* ignore \c \C \m and \M after '$' */
2623 while (p[0] == '\\' && (p[1] == 'c' || p[1] == 'C'
2624 || p[1] == 'm' || p[1] == 'M' || p[1] == 'Z'))
2625 p += 2;
2626 if (p[0] == NUL
2627 || (p[0] == '\\'
2628 && (p[1] == '|' || p[1] == '&' || p[1] == ')'
2629 || p[1] == 'n'))
2630 || reg_magic == MAGIC_ALL)
2631 curchr = Magic('$');
2632 }
2633 break;
2634 case '\\':
2635 {
2636 int c = regparse[1];
2637
2638 if (c == NUL)
2639 curchr = '\\'; /* trailing '\' */
2640 else if (
2641#ifdef EBCDIC
2642 vim_strchr(META, c)
2643#else
2644 c <= '~' && META_flags[c]
2645#endif
2646 )
2647 {
2648 /*
2649 * META contains everything that may be magic sometimes,
2650 * except ^ and $ ("\^" and "\$" are only magic after
2651 * "\v"). We now fetch the next character and toggle its
2652 * magicness. Therefore, \ is so meta-magic that it is
2653 * not in META.
2654 */
2655 curchr = -1;
2656 prev_at_start = at_start;
2657 at_start = FALSE; /* be able to say "/\*ptr" */
2658 ++regparse;
Bram Moolenaardf177f62005-02-22 08:39:57 +00002659 ++after_slash;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 peekchr();
2661 --regparse;
Bram Moolenaardf177f62005-02-22 08:39:57 +00002662 --after_slash;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663 curchr = toggle_Magic(curchr);
2664 }
2665 else if (vim_strchr(REGEXP_ABBR, c))
2666 {
2667 /*
2668 * Handle abbreviations, like "\t" for TAB -- webb
2669 */
2670 curchr = backslash_trans(c);
2671 }
2672 else if (reg_magic == MAGIC_NONE && (c == '$' || c == '^'))
2673 curchr = toggle_Magic(c);
2674 else
2675 {
2676 /*
2677 * Next character can never be (made) magic?
2678 * Then backslashing it won't do anything.
2679 */
2680#ifdef FEAT_MBYTE
2681 if (has_mbyte)
2682 curchr = (*mb_ptr2char)(regparse + 1);
2683 else
2684#endif
2685 curchr = c;
2686 }
2687 break;
2688 }
2689
2690#ifdef FEAT_MBYTE
2691 default:
2692 if (has_mbyte)
2693 curchr = (*mb_ptr2char)(regparse);
2694#endif
2695 }
2696 }
2697
2698 return curchr;
2699}
2700
2701/*
2702 * Eat one lexed character. Do this in a way that we can undo it.
2703 */
2704 static void
2705skipchr()
2706{
2707 /* peekchr() eats a backslash, do the same here */
2708 if (*regparse == '\\')
2709 prevchr_len = 1;
2710 else
2711 prevchr_len = 0;
2712 if (regparse[prevchr_len] != NUL)
2713 {
2714#ifdef FEAT_MBYTE
2715 if (has_mbyte)
2716 prevchr_len += (*mb_ptr2len_check)(regparse + prevchr_len);
2717 else
2718#endif
2719 ++prevchr_len;
2720 }
2721 regparse += prevchr_len;
2722 prev_at_start = at_start;
2723 at_start = FALSE;
2724 prevprevchr = prevchr;
2725 prevchr = curchr;
2726 curchr = nextchr; /* use previously unget char, or -1 */
2727 nextchr = -1;
2728}
2729
2730/*
2731 * Skip a character while keeping the value of prev_at_start for at_start.
2732 * prevchr and prevprevchr are also kept.
2733 */
2734 static void
2735skipchr_keepstart()
2736{
2737 int as = prev_at_start;
2738 int pr = prevchr;
2739 int prpr = prevprevchr;
2740
2741 skipchr();
2742 at_start = as;
2743 prevchr = pr;
2744 prevprevchr = prpr;
2745}
2746
2747 static int
2748getchr()
2749{
2750 int chr = peekchr();
2751
2752 skipchr();
2753 return chr;
2754}
2755
2756/*
2757 * put character back. Works only once!
2758 */
2759 static void
2760ungetchr()
2761{
2762 nextchr = curchr;
2763 curchr = prevchr;
2764 prevchr = prevprevchr;
2765 at_start = prev_at_start;
2766 prev_at_start = FALSE;
2767
2768 /* Backup regparse, so that it's at the same position as before the
2769 * getchr(). */
2770 regparse -= prevchr_len;
2771}
2772
2773/*
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002774 * Get and return the value of the hex string at the current position.
2775 * Return -1 if there is no valid hex number.
2776 * The position is updated:
Bram Moolenaarc0197e22004-09-13 20:26:32 +00002777 * blahblah\%x20asdf
2778 * before-^ ^-after
2779 * The parameter controls the maximum number of input characters. This will be
2780 * 2 when reading a \%x20 sequence and 4 when reading a \%u20AC sequence.
2781 */
2782 static int
2783gethexchrs(maxinputlen)
2784 int maxinputlen;
2785{
2786 int nr = 0;
2787 int c;
2788 int i;
2789
2790 for (i = 0; i < maxinputlen; ++i)
2791 {
2792 c = regparse[0];
2793 if (!vim_isxdigit(c))
2794 break;
2795 nr <<= 4;
2796 nr |= hex2nr(c);
2797 ++regparse;
2798 }
2799
2800 if (i == 0)
2801 return -1;
2802 return nr;
2803}
2804
2805/*
2806 * get and return the value of the decimal string immediately after the
2807 * current position. Return -1 for invalid. Consumes all digits.
2808 */
2809 static int
2810getdecchrs()
2811{
2812 int nr = 0;
2813 int c;
2814 int i;
2815
2816 for (i = 0; ; ++i)
2817 {
2818 c = regparse[0];
2819 if (c < '0' || c > '9')
2820 break;
2821 nr *= 10;
2822 nr += c - '0';
2823 ++regparse;
2824 }
2825
2826 if (i == 0)
2827 return -1;
2828 return nr;
2829}
2830
2831/*
2832 * get and return the value of the octal string immediately after the current
2833 * position. Return -1 for invalid, or 0-255 for valid. Smart enough to handle
2834 * numbers > 377 correctly (for example, 400 is treated as 40) and doesn't
2835 * treat 8 or 9 as recognised characters. Position is updated:
2836 * blahblah\%o210asdf
2837 * before-^ ^-after
2838 */
2839 static int
2840getoctchrs()
2841{
2842 int nr = 0;
2843 int c;
2844 int i;
2845
2846 for (i = 0; i < 3 && nr < 040; ++i)
2847 {
2848 c = regparse[0];
2849 if (c < '0' || c > '7')
2850 break;
2851 nr <<= 3;
2852 nr |= hex2nr(c);
2853 ++regparse;
2854 }
2855
2856 if (i == 0)
2857 return -1;
2858 return nr;
2859}
2860
2861/*
2862 * Get a number after a backslash that is inside [].
2863 * When nothing is recognized return a backslash.
2864 */
2865 static int
2866coll_get_char()
2867{
2868 int nr = -1;
2869
2870 switch (*regparse++)
2871 {
2872 case 'd': nr = getdecchrs(); break;
2873 case 'o': nr = getoctchrs(); break;
2874 case 'x': nr = gethexchrs(2); break;
2875 case 'u': nr = gethexchrs(4); break;
2876 case 'U': nr = gethexchrs(8); break;
2877 }
2878 if (nr < 0)
2879 {
2880 /* If getting the number fails be backwards compatible: the character
2881 * is a backslash. */
2882 --regparse;
2883 nr = '\\';
2884 }
2885 return nr;
2886}
2887
2888/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 * read_limits - Read two integers to be taken as a minimum and maximum.
2890 * If the first character is '-', then the range is reversed.
2891 * Should end with 'end'. If minval is missing, zero is default, if maxval is
2892 * missing, a very big number is the default.
2893 */
2894 static int
2895read_limits(minval, maxval)
2896 long *minval;
2897 long *maxval;
2898{
2899 int reverse = FALSE;
2900 char_u *first_char;
2901 long tmp;
2902
2903 if (*regparse == '-')
2904 {
2905 /* Starts with '-', so reverse the range later */
2906 regparse++;
2907 reverse = TRUE;
2908 }
2909 first_char = regparse;
2910 *minval = getdigits(&regparse);
2911 if (*regparse == ',') /* There is a comma */
2912 {
2913 if (vim_isdigit(*++regparse))
2914 *maxval = getdigits(&regparse);
2915 else
2916 *maxval = MAX_LIMIT;
2917 }
2918 else if (VIM_ISDIGIT(*first_char))
2919 *maxval = *minval; /* It was \{n} or \{-n} */
2920 else
2921 *maxval = MAX_LIMIT; /* It was \{} or \{-} */
2922 if (*regparse == '\\')
2923 regparse++; /* Allow either \{...} or \{...\} */
Bram Moolenaardf177f62005-02-22 08:39:57 +00002924 if (*regparse != '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 {
2926 sprintf((char *)IObuff, _("E554: Syntax error in %s{...}"),
2927 reg_magic == MAGIC_ALL ? "" : "\\");
2928 EMSG_RET_FAIL(IObuff);
2929 }
2930
2931 /*
2932 * Reverse the range if there was a '-', or make sure it is in the right
2933 * order otherwise.
2934 */
2935 if ((!reverse && *minval > *maxval) || (reverse && *minval < *maxval))
2936 {
2937 tmp = *minval;
2938 *minval = *maxval;
2939 *maxval = tmp;
2940 }
2941 skipchr(); /* let's be friends with the lexer again */
2942 return OK;
2943}
2944
2945/*
2946 * vim_regexec and friends
2947 */
2948
2949/*
2950 * Global work variables for vim_regexec().
2951 */
2952
2953/* The current match-position is remembered with these variables: */
2954static linenr_T reglnum; /* line number, relative to first line */
2955static char_u *regline; /* start of current line */
2956static char_u *reginput; /* current input, points into "regline" */
2957
2958static int need_clear_subexpr; /* subexpressions still need to be
2959 * cleared */
2960#ifdef FEAT_SYN_HL
2961static int need_clear_zsubexpr = FALSE; /* extmatch subexpressions
2962 * still need to be cleared */
2963#endif
2964
2965static int out_of_stack; /* TRUE when ran out of stack space */
2966
2967/*
2968 * Structure used to save the current input state, when it needs to be
2969 * restored after trying a match. Used by reg_save() and reg_restore().
2970 */
2971typedef struct
2972{
2973 union
2974 {
2975 char_u *ptr; /* reginput pointer, for single-line regexp */
2976 lpos_T pos; /* reginput pos, for multi-line regexp */
2977 } rs_u;
2978} regsave_T;
2979
2980/* struct to save start/end pointer/position in for \(\) */
2981typedef struct
2982{
2983 union
2984 {
2985 char_u *ptr;
2986 lpos_T pos;
2987 } se_u;
2988} save_se_T;
2989
2990static char_u *reg_getline __ARGS((linenr_T lnum));
2991static long vim_regexec_both __ARGS((char_u *line, colnr_T col));
2992static long regtry __ARGS((regprog_T *prog, colnr_T col));
2993static void cleanup_subexpr __ARGS((void));
2994#ifdef FEAT_SYN_HL
2995static void cleanup_zsubexpr __ARGS((void));
2996#endif
2997static void reg_nextline __ARGS((void));
2998static void reg_save __ARGS((regsave_T *save));
2999static void reg_restore __ARGS((regsave_T *save));
3000static int reg_save_equal __ARGS((regsave_T *save));
3001static void save_se_multi __ARGS((save_se_T *savep, lpos_T *posp));
3002static void save_se_one __ARGS((save_se_T *savep, char_u **pp));
3003
3004/* Save the sub-expressions before attempting a match. */
3005#define save_se(savep, posp, pp) \
3006 REG_MULTI ? save_se_multi((savep), (posp)) : save_se_one((savep), (pp))
3007
3008/* After a failed match restore the sub-expressions. */
3009#define restore_se(savep, posp, pp) { \
3010 if (REG_MULTI) \
3011 *(posp) = (savep)->se_u.pos; \
3012 else \
3013 *(pp) = (savep)->se_u.ptr; }
3014
3015static int re_num_cmp __ARGS((long_u val, char_u *scan));
Bram Moolenaardf177f62005-02-22 08:39:57 +00003016static int regmatch __ARGS((char_u *prog, regsave_T *startp));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017static int regrepeat __ARGS((char_u *p, long maxcount));
3018
3019#ifdef DEBUG
3020int regnarrate = 0;
3021#endif
3022
3023/*
3024 * Internal copy of 'ignorecase'. It is set at each call to vim_regexec().
3025 * Normally it gets the value of "rm_ic" or "rmm_ic", but when the pattern
3026 * contains '\c' or '\C' the value is overruled.
3027 */
3028static int ireg_ic;
3029
3030#ifdef FEAT_MBYTE
3031/*
3032 * Similar to ireg_ic, but only for 'combining' characters. Set with \Z flag
3033 * in the regexp. Defaults to false, always.
3034 */
3035static int ireg_icombine;
3036#endif
3037
3038/*
3039 * Sometimes need to save a copy of a line. Since alloc()/free() is very
3040 * slow, we keep one allocated piece of memory and only re-allocate it when
3041 * it's too small. It's freed in vim_regexec_both() when finished.
3042 */
3043static char_u *reg_tofree;
3044static unsigned reg_tofreelen;
3045
3046/*
3047 * These variables are set when executing a regexp to speed up the execution.
3048 * Which ones are set depends on whethere a single-line or multi-line match is
3049 * done:
3050 * single-line multi-line
3051 * reg_match &regmatch_T NULL
3052 * reg_mmatch NULL &regmmatch_T
3053 * reg_startp reg_match->startp <invalid>
3054 * reg_endp reg_match->endp <invalid>
3055 * reg_startpos <invalid> reg_mmatch->startpos
3056 * reg_endpos <invalid> reg_mmatch->endpos
3057 * reg_win NULL window in which to search
3058 * reg_buf <invalid> buffer in which to search
3059 * reg_firstlnum <invalid> first line in which to search
3060 * reg_maxline 0 last line nr
3061 * reg_line_lbr FALSE or TRUE FALSE
3062 */
3063static regmatch_T *reg_match;
3064static regmmatch_T *reg_mmatch;
3065static char_u **reg_startp = NULL;
3066static char_u **reg_endp = NULL;
3067static lpos_T *reg_startpos = NULL;
3068static lpos_T *reg_endpos = NULL;
3069static win_T *reg_win;
3070static buf_T *reg_buf;
3071static linenr_T reg_firstlnum;
3072static linenr_T reg_maxline;
3073static int reg_line_lbr; /* "\n" in string is line break */
3074
3075/*
3076 * Get pointer to the line "lnum", which is relative to "reg_firstlnum".
3077 */
3078 static char_u *
3079reg_getline(lnum)
3080 linenr_T lnum;
3081{
3082 /* when looking behind for a match/no-match lnum is negative. But we
3083 * can't go before line 1 */
3084 if (reg_firstlnum + lnum < 1)
3085 return NULL;
3086 return ml_get_buf(reg_buf, reg_firstlnum + lnum, FALSE);
3087}
3088
3089static regsave_T behind_pos;
3090
3091#ifdef FEAT_SYN_HL
3092static char_u *reg_startzp[NSUBEXP]; /* Workspace to mark beginning */
3093static char_u *reg_endzp[NSUBEXP]; /* and end of \z(...\) matches */
3094static lpos_T reg_startzpos[NSUBEXP]; /* idem, beginning pos */
3095static lpos_T reg_endzpos[NSUBEXP]; /* idem, end pos */
3096#endif
3097
3098/* TRUE if using multi-line regexp. */
3099#define REG_MULTI (reg_match == NULL)
3100
3101/*
3102 * Match a regexp against a string.
3103 * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
3104 * Uses curbuf for line count and 'iskeyword'.
3105 *
3106 * Return TRUE if there is a match, FALSE if not.
3107 */
3108 int
3109vim_regexec(rmp, line, col)
3110 regmatch_T *rmp;
3111 char_u *line; /* string to match against */
3112 colnr_T col; /* column to start looking for match */
3113{
3114 reg_match = rmp;
3115 reg_mmatch = NULL;
3116 reg_maxline = 0;
3117 reg_line_lbr = FALSE;
3118 reg_win = NULL;
3119 ireg_ic = rmp->rm_ic;
3120#ifdef FEAT_MBYTE
3121 ireg_icombine = FALSE;
3122#endif
3123 return (vim_regexec_both(line, col) != 0);
3124}
3125
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003126#if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) \
3127 || defined(FIND_REPLACE_DIALOG) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128/*
3129 * Like vim_regexec(), but consider a "\n" in "line" to be a line break.
3130 */
3131 int
3132vim_regexec_nl(rmp, line, col)
3133 regmatch_T *rmp;
3134 char_u *line; /* string to match against */
3135 colnr_T col; /* column to start looking for match */
3136{
3137 reg_match = rmp;
3138 reg_mmatch = NULL;
3139 reg_maxline = 0;
3140 reg_line_lbr = TRUE;
3141 reg_win = NULL;
3142 ireg_ic = rmp->rm_ic;
3143#ifdef FEAT_MBYTE
3144 ireg_icombine = FALSE;
3145#endif
3146 return (vim_regexec_both(line, col) != 0);
3147}
3148#endif
3149
3150/*
3151 * Match a regexp against multiple lines.
3152 * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
3153 * Uses curbuf for line count and 'iskeyword'.
3154 *
3155 * Return zero if there is no match. Return number of lines contained in the
3156 * match otherwise.
3157 */
3158 long
3159vim_regexec_multi(rmp, win, buf, lnum, col)
3160 regmmatch_T *rmp;
3161 win_T *win; /* window in which to search or NULL */
3162 buf_T *buf; /* buffer in which to search */
3163 linenr_T lnum; /* nr of line to start looking for match */
3164 colnr_T col; /* column to start looking for match */
3165{
3166 long r;
3167 buf_T *save_curbuf = curbuf;
3168
3169 reg_match = NULL;
3170 reg_mmatch = rmp;
3171 reg_buf = buf;
3172 reg_win = win;
3173 reg_firstlnum = lnum;
3174 reg_maxline = reg_buf->b_ml.ml_line_count - lnum;
3175 reg_line_lbr = FALSE;
3176 ireg_ic = rmp->rmm_ic;
3177#ifdef FEAT_MBYTE
3178 ireg_icombine = FALSE;
3179#endif
3180
3181 /* Need to switch to buffer "buf" to make vim_iswordc() work. */
3182 curbuf = buf;
3183 r = vim_regexec_both(NULL, col);
3184 curbuf = save_curbuf;
3185
3186 return r;
3187}
3188
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00003189#if 0 /* this does not appear to work... */
3190# ifdef __MINGW32__
3191# define MINGW_TRY
3192# endif
3193#endif
3194
3195#ifdef MINGW_TRY
3196/*
3197 * Special assembly code for MingW to simulate __try / __except.
3198 * Does not work with the optimizer!
3199 */
3200# include <excpt.h>
3201
3202static void *ESP_save; /* used as _ESP below */
3203static void *EBP_save; /* used as _EBP below */
3204
3205__attribute__ ((cdecl))
3206 EXCEPTION_DISPOSITION
3207 _except_regexec_handler(
3208 struct _EXCEPTION_RECORD *ExceptionRecord,
3209 void *EstablisherFrame,
3210 struct _CONTEXT *ContextRecord,
3211 void *DispatcherContext)
3212{
3213 __asm__ __volatile__ (
3214 "jmp regexec_reentry");
3215 return 0; /* Function does not return */
3216}
3217#endif
3218
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219/*
3220 * Match a regexp against a string ("line" points to the string) or multiple
3221 * lines ("line" is NULL, use reg_getline()).
3222 */
3223#ifdef HAVE_SETJMP_H
3224 static long
3225vim_regexec_both(line_arg, col_arg)
3226 char_u *line_arg;
3227 colnr_T col_arg; /* column to start looking for match */
3228#else
3229 static long
3230vim_regexec_both(line, col)
3231 char_u *line;
3232 colnr_T col; /* column to start looking for match */
3233#endif
3234{
3235 regprog_T *prog;
3236 char_u *s;
3237 long retval;
3238#ifdef HAVE_SETJMP_H
3239 char_u *line;
3240 colnr_T col;
Bram Moolenaar748bf032005-02-02 23:04:36 +00003241 int did_mch_startjmp = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242#endif
3243
3244 reg_tofree = NULL;
3245
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246#ifdef HAVE_SETJMP_H
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 /* Trick to avoid "might be clobbered by `longjmp'" warning from gcc. */
3248 line = line_arg;
3249 col = col_arg;
3250#endif
3251 retval = 0L;
3252
3253 if (REG_MULTI)
3254 {
3255 prog = reg_mmatch->regprog;
3256 line = reg_getline((linenr_T)0);
3257 reg_startpos = reg_mmatch->startpos;
3258 reg_endpos = reg_mmatch->endpos;
3259 }
3260 else
3261 {
3262 prog = reg_match->regprog;
3263 reg_startp = reg_match->startp;
3264 reg_endp = reg_match->endp;
3265 }
3266
3267 /* Be paranoid... */
3268 if (prog == NULL || line == NULL)
3269 {
3270 EMSG(_(e_null));
3271 goto theend;
3272 }
3273
3274 /* Check validity of program. */
3275 if (prog_magic_wrong())
3276 goto theend;
3277
3278 /* If pattern contains "\c" or "\C": overrule value of ireg_ic */
3279 if (prog->regflags & RF_ICASE)
3280 ireg_ic = TRUE;
3281 else if (prog->regflags & RF_NOICASE)
3282 ireg_ic = FALSE;
3283
3284#ifdef FEAT_MBYTE
3285 /* If pattern contains "\Z" overrule value of ireg_icombine */
3286 if (prog->regflags & RF_ICOMBINE)
3287 ireg_icombine = TRUE;
3288#endif
3289
3290 /* If there is a "must appear" string, look for it. */
3291 if (prog->regmust != NULL)
3292 {
3293 int c;
3294
3295#ifdef FEAT_MBYTE
3296 if (has_mbyte)
3297 c = (*mb_ptr2char)(prog->regmust);
3298 else
3299#endif
3300 c = *prog->regmust;
3301 s = line + col;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003302
3303 /*
3304 * This is used very often, esp. for ":global". Use three versions of
3305 * the loop to avoid overhead of conditions.
3306 */
3307 if (!ireg_ic
3308#ifdef FEAT_MBYTE
3309 && !has_mbyte
3310#endif
3311 )
3312 while ((s = vim_strbyte(s, c)) != NULL)
3313 {
3314 if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0)
3315 break; /* Found it. */
3316 ++s;
3317 }
3318#ifdef FEAT_MBYTE
3319 else if (!ireg_ic || (!enc_utf8 && mb_char2len(c) > 1))
3320 while ((s = vim_strchr(s, c)) != NULL)
3321 {
3322 if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0)
3323 break; /* Found it. */
3324 mb_ptr_adv(s);
3325 }
3326#endif
3327 else
3328 while ((s = cstrchr(s, c)) != NULL)
3329 {
3330 if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0)
3331 break; /* Found it. */
3332 mb_ptr_adv(s);
3333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 if (s == NULL) /* Not present. */
3335 goto theend;
3336 }
3337
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00003338#ifdef MINGW_TRY
3339 /* Ugly assembly code that is necessary to simulate "__try". */
3340 __asm__ __volatile__ (
3341 "movl %esp, _ESP_save" "\n\t"
3342 "movl %ebp, _EBP_save");
3343
3344 __asm__ __volatile__ (
3345 "pushl $__except_regexec_handler" "\n\t"
3346 "pushl %fs:0" "\n\t"
3347 "mov %esp, %fs:0");
3348#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00003349#ifdef HAVE_TRY_EXCEPT
3350 __try
3351 {
3352#endif
3353
3354#ifdef HAVE_SETJMP_H
3355 /*
3356 * Matching with a regexp may cause a very deep recursive call of
3357 * regmatch(). Vim will crash when running out of stack space. Catch
3358 * this here if the system supports it.
3359 * It's a bit slow, do it after the check for "regmust".
3360 * Don't do it if the caller already set it up.
3361 */
3362 if (!lc_active)
3363 {
3364 did_mch_startjmp = TRUE;
3365 mch_startjmp();
3366 if (SETJMP(lc_jump_env) != 0)
3367 {
3368 mch_didjmp();
3369# ifdef SIGHASARG
3370 if (lc_signal != SIGINT)
3371# endif
3372 EMSG(_(e_complex));
3373 retval = 0L;
3374 goto inner_end;
3375 }
3376 }
3377#endif
3378
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 regline = line;
3380 reglnum = 0;
3381 out_of_stack = FALSE;
3382
3383 /* Simplest case: Anchored match need be tried only once. */
3384 if (prog->reganch)
3385 {
3386 int c;
3387
3388#ifdef FEAT_MBYTE
3389 if (has_mbyte)
3390 c = (*mb_ptr2char)(regline + col);
3391 else
3392#endif
3393 c = regline[col];
3394 if (prog->regstart == NUL
3395 || prog->regstart == c
3396 || (ireg_ic && ((
3397#ifdef FEAT_MBYTE
3398 (enc_utf8 && utf_fold(prog->regstart) == utf_fold(c)))
3399 || (c < 255 && prog->regstart < 255 &&
3400#endif
3401 TOLOWER_LOC(prog->regstart) == TOLOWER_LOC(c)))))
3402 retval = regtry(prog, col);
3403 else
3404 retval = 0;
3405 }
3406 else
3407 {
3408 /* Messy cases: unanchored match. */
3409 while (!got_int && !out_of_stack)
3410 {
3411 if (prog->regstart != NUL)
3412 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00003413 /* Skip until the char we know it must start with.
3414 * Used often, do some work to avoid call overhead. */
3415 if (!ireg_ic
3416#ifdef FEAT_MBYTE
3417 && !has_mbyte
3418#endif
3419 )
3420 s = vim_strbyte(regline + col, prog->regstart);
3421 else
3422 s = cstrchr(regline + col, prog->regstart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 if (s == NULL)
3424 {
3425 retval = 0;
3426 break;
3427 }
3428 col = (int)(s - regline);
3429 }
3430
3431 retval = regtry(prog, col);
3432 if (retval > 0)
3433 break;
3434
3435 /* if not currently on the first line, get it again */
3436 if (reglnum != 0)
3437 {
3438 regline = reg_getline((linenr_T)0);
3439 reglnum = 0;
3440 }
3441 if (regline[col] == NUL)
3442 break;
3443#ifdef FEAT_MBYTE
3444 if (has_mbyte)
3445 col += (*mb_ptr2len_check)(regline + col);
3446 else
3447#endif
3448 ++col;
3449 }
3450 }
3451
3452 if (out_of_stack)
Bram Moolenaar748bf032005-02-02 23:04:36 +00003453 EMSG(_(e_outofstack));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454
Bram Moolenaar748bf032005-02-02 23:04:36 +00003455#ifdef HAVE_SETJMP_H
3456inner_end:
Bram Moolenaar05159a02005-02-26 23:04:13 +00003457 if (did_mch_startjmp)
3458 mch_endjmp();
Bram Moolenaar748bf032005-02-02 23:04:36 +00003459#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460#ifdef HAVE_TRY_EXCEPT
3461 }
3462 __except(EXCEPTION_EXECUTE_HANDLER)
3463 {
3464 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
3465 {
3466 RESETSTKOFLW();
Bram Moolenaar748bf032005-02-02 23:04:36 +00003467 EMSG(_(e_outofstack));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468 }
3469 else
Bram Moolenaar748bf032005-02-02 23:04:36 +00003470 EMSG(_(e_complex));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471 retval = 0L;
3472 }
3473#endif
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00003474#ifdef MINGW_TRY
3475 __asm__ __volatile__ (
3476 "jmp regexec_pop" "\n"
3477 "regexec_reentry:" "\n\t"
3478 "movl _ESP_save, %esp" "\n\t"
3479 "movl _EBP_save, %ebp");
3480
3481 EMSG(_(e_complex));
3482 retval = 0L;
3483
3484 __asm__ __volatile__ (
3485 "regexec_pop:" "\n\t"
3486 "mov (%esp), %eax" "\n\t"
3487 "mov %eax, %fs:0" "\n\t"
3488 "add $8, %esp");
3489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490
3491theend:
3492 /* Didn't find a match. */
3493 vim_free(reg_tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 return retval;
3495}
3496
3497#ifdef FEAT_SYN_HL
3498static reg_extmatch_T *make_extmatch __ARGS((void));
3499
3500/*
3501 * Create a new extmatch and mark it as referenced once.
3502 */
3503 static reg_extmatch_T *
3504make_extmatch()
3505{
3506 reg_extmatch_T *em;
3507
3508 em = (reg_extmatch_T *)alloc_clear((unsigned)sizeof(reg_extmatch_T));
3509 if (em != NULL)
3510 em->refcnt = 1;
3511 return em;
3512}
3513
3514/*
3515 * Add a reference to an extmatch.
3516 */
3517 reg_extmatch_T *
3518ref_extmatch(em)
3519 reg_extmatch_T *em;
3520{
3521 if (em != NULL)
3522 em->refcnt++;
3523 return em;
3524}
3525
3526/*
3527 * Remove a reference to an extmatch. If there are no references left, free
3528 * the info.
3529 */
3530 void
3531unref_extmatch(em)
3532 reg_extmatch_T *em;
3533{
3534 int i;
3535
3536 if (em != NULL && --em->refcnt <= 0)
3537 {
3538 for (i = 0; i < NSUBEXP; ++i)
3539 vim_free(em->matches[i]);
3540 vim_free(em);
3541 }
3542}
3543#endif
3544
3545/*
3546 * regtry - try match of "prog" with at regline["col"].
3547 * Returns 0 for failure, number of lines contained in the match otherwise.
3548 */
3549 static long
3550regtry(prog, col)
3551 regprog_T *prog;
3552 colnr_T col;
3553{
3554 reginput = regline + col;
3555 need_clear_subexpr = TRUE;
3556#ifdef FEAT_SYN_HL
3557 /* Clear the external match subpointers if necessary. */
3558 if (prog->reghasz == REX_SET)
3559 need_clear_zsubexpr = TRUE;
3560#endif
3561
Bram Moolenaardf177f62005-02-22 08:39:57 +00003562 if (regmatch(prog->program + 1, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 {
3564 cleanup_subexpr();
3565 if (REG_MULTI)
3566 {
3567 if (reg_startpos[0].lnum < 0)
3568 {
3569 reg_startpos[0].lnum = 0;
3570 reg_startpos[0].col = col;
3571 }
3572 if (reg_endpos[0].lnum < 0)
3573 {
3574 reg_endpos[0].lnum = reglnum;
3575 reg_endpos[0].col = (int)(reginput - regline);
3576 }
3577 else
3578 /* Use line number of "\ze". */
3579 reglnum = reg_endpos[0].lnum;
3580 }
3581 else
3582 {
3583 if (reg_startp[0] == NULL)
3584 reg_startp[0] = regline + col;
3585 if (reg_endp[0] == NULL)
3586 reg_endp[0] = reginput;
3587 }
3588#ifdef FEAT_SYN_HL
3589 /* Package any found \z(...\) matches for export. Default is none. */
3590 unref_extmatch(re_extmatch_out);
3591 re_extmatch_out = NULL;
3592
3593 if (prog->reghasz == REX_SET)
3594 {
3595 int i;
3596
3597 cleanup_zsubexpr();
3598 re_extmatch_out = make_extmatch();
3599 for (i = 0; i < NSUBEXP; i++)
3600 {
3601 if (REG_MULTI)
3602 {
3603 /* Only accept single line matches. */
3604 if (reg_startzpos[i].lnum >= 0
3605 && reg_endzpos[i].lnum == reg_startzpos[i].lnum)
3606 re_extmatch_out->matches[i] =
3607 vim_strnsave(reg_getline(reg_startzpos[i].lnum)
3608 + reg_startzpos[i].col,
3609 reg_endzpos[i].col - reg_startzpos[i].col);
3610 }
3611 else
3612 {
3613 if (reg_startzp[i] != NULL && reg_endzp[i] != NULL)
3614 re_extmatch_out->matches[i] =
3615 vim_strnsave(reg_startzp[i],
3616 (int)(reg_endzp[i] - reg_startzp[i]));
3617 }
3618 }
3619 }
3620#endif
3621 return 1 + reglnum;
3622 }
3623 return 0;
3624}
3625
3626#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627static int reg_prev_class __ARGS((void));
3628
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629/*
3630 * Get class of previous character.
3631 */
3632 static int
3633reg_prev_class()
3634{
3635 if (reginput > regline)
3636 return mb_get_class(reginput - 1
3637 - (*mb_head_off)(regline, reginput - 1));
3638 return -1;
3639}
3640
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003642#define ADVANCE_REGINPUT() mb_ptr_adv(reginput)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643
3644/*
3645 * The arguments from BRACE_LIMITS are stored here. They are actually local
3646 * to regmatch(), but they are here to reduce the amount of stack space used
3647 * (it can be called recursively many times).
3648 */
3649static long bl_minval;
3650static long bl_maxval;
3651
3652/*
3653 * regmatch - main matching routine
3654 *
3655 * Conceptually the strategy is simple: Check to see whether the current
3656 * node matches, call self recursively to see whether the rest matches,
3657 * and then act accordingly. In practice we make some effort to avoid
3658 * recursion, in particular by going through "ordinary" nodes (that don't
3659 * need to know whether the rest of the match failed) by a loop instead of
3660 * by recursion.
3661 *
3662 * Returns TRUE when there is a match. Leaves reginput and reglnum just after
3663 * the last matched character.
3664 * Returns FALSE when there is no match. Leaves reginput and reglnum in an
3665 * undefined state!
3666 */
3667 static int
Bram Moolenaardf177f62005-02-22 08:39:57 +00003668regmatch(scan, startp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003669 char_u *scan; /* Current node. */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003670 regsave_T *startp; /* start position for BACK */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671{
3672 char_u *next; /* Next node. */
3673 int op;
3674 int c;
3675
3676#ifdef HAVE_GETRLIMIT
3677 /* Check if we are running out of stack space. Could be caused by
3678 * recursively calling ourselves. */
3679 if (out_of_stack || mch_stackcheck((char *)&op) == FAIL)
3680 {
3681 out_of_stack = TRUE;
3682 return FALSE;
3683 }
3684#endif
3685
3686 /* Some patterns my cause a long time to match, even though they are not
3687 * illegal. E.g., "\([a-z]\+\)\+Q". Allow breaking them with CTRL-C. */
3688 fast_breakcheck();
3689
3690#ifdef DEBUG
3691 if (scan != NULL && regnarrate)
3692 {
3693 mch_errmsg(regprop(scan));
3694 mch_errmsg("(\n");
3695 }
3696#endif
3697 while (scan != NULL)
3698 {
3699 if (got_int || out_of_stack)
3700 return FALSE;
3701#ifdef DEBUG
3702 if (regnarrate)
3703 {
3704 mch_errmsg(regprop(scan));
3705 mch_errmsg("...\n");
3706# ifdef FEAT_SYN_HL
3707 if (re_extmatch_in != NULL)
3708 {
3709 int i;
3710
3711 mch_errmsg(_("External submatches:\n"));
3712 for (i = 0; i < NSUBEXP; i++)
3713 {
3714 mch_errmsg(" \"");
3715 if (re_extmatch_in->matches[i] != NULL)
3716 mch_errmsg(re_extmatch_in->matches[i]);
3717 mch_errmsg("\"\n");
3718 }
3719 }
3720# endif
3721 }
3722#endif
3723 next = regnext(scan);
3724
3725 op = OP(scan);
3726 /* Check for character class with NL added. */
3727 if (WITH_NL(op) && *reginput == NUL && reglnum < reg_maxline)
3728 {
3729 reg_nextline();
3730 }
3731 else if (reg_line_lbr && WITH_NL(op) && *reginput == '\n')
3732 {
3733 ADVANCE_REGINPUT();
3734 }
3735 else
3736 {
3737 if (WITH_NL(op))
3738 op -= ADD_NL;
3739#ifdef FEAT_MBYTE
3740 if (has_mbyte)
3741 c = (*mb_ptr2char)(reginput);
3742 else
3743#endif
3744 c = *reginput;
3745 switch (op)
3746 {
3747 case BOL:
3748 if (reginput != regline)
3749 return FALSE;
3750 break;
3751
3752 case EOL:
3753 if (c != NUL)
3754 return FALSE;
3755 break;
3756
3757 case RE_BOF:
3758 /* Passing -1 to the getline() function provided for the search
3759 * should always return NULL if the current line is the first
3760 * line of the file. */
3761 if (reglnum != 0 || reginput != regline
3762 || (REG_MULTI && reg_getline((linenr_T)-1) != NULL))
3763 return FALSE;
3764 break;
3765
3766 case RE_EOF:
3767 if (reglnum != reg_maxline || c != NUL)
3768 return FALSE;
3769 break;
3770
3771 case CURSOR:
3772 /* Check if the buffer is in a window and compare the
3773 * reg_win->w_cursor position to the match position. */
3774 if (reg_win == NULL
3775 || (reglnum + reg_firstlnum != reg_win->w_cursor.lnum)
3776 || ((colnr_T)(reginput - regline) != reg_win->w_cursor.col))
3777 return FALSE;
3778 break;
3779
3780 case RE_LNUM:
3781 if (!REG_MULTI || !re_num_cmp((long_u)(reglnum + reg_firstlnum),
3782 scan))
3783 return FALSE;
3784 break;
3785
3786 case RE_COL:
3787 if (!re_num_cmp((long_u)(reginput - regline) + 1, scan))
3788 return FALSE;
3789 break;
3790
3791 case RE_VCOL:
3792 if (!re_num_cmp((long_u)win_linetabsize(
3793 reg_win == NULL ? curwin : reg_win,
3794 regline, (colnr_T)(reginput - regline)) + 1, scan))
3795 return FALSE;
3796 break;
3797
3798 case BOW: /* \<word; reginput points to w */
3799 if (c == NUL) /* Can't match at end of line */
3800 return FALSE;
3801#ifdef FEAT_MBYTE
3802 if (has_mbyte)
3803 {
3804 int this_class;
3805
3806 /* Get class of current and previous char (if it exists). */
3807 this_class = mb_get_class(reginput);
3808 if (this_class <= 1)
3809 return FALSE; /* not on a word at all */
3810 if (reg_prev_class() == this_class)
3811 return FALSE; /* previous char is in same word */
3812 }
3813#endif
3814 else
3815 {
3816 if (!vim_iswordc(c)
3817 || (reginput > regline && vim_iswordc(reginput[-1])))
3818 return FALSE;
3819 }
3820 break;
3821
3822 case EOW: /* word\>; reginput points after d */
3823 if (reginput == regline) /* Can't match at start of line */
3824 return FALSE;
3825#ifdef FEAT_MBYTE
3826 if (has_mbyte)
3827 {
3828 int this_class, prev_class;
3829
3830 /* Get class of current and previous char (if it exists). */
3831 this_class = mb_get_class(reginput);
3832 prev_class = reg_prev_class();
3833 if (this_class == prev_class)
3834 return FALSE;
3835 if (prev_class == 0 || prev_class == 1)
3836 return FALSE;
3837 }
3838 else
3839#endif
3840 {
3841 if (!vim_iswordc(reginput[-1]))
3842 return FALSE;
3843 if (reginput[0] != NUL && vim_iswordc(c))
3844 return FALSE;
3845 }
3846 break; /* Matched with EOW */
3847
3848 case ANY:
3849 if (c == NUL)
3850 return FALSE;
3851 ADVANCE_REGINPUT();
3852 break;
3853
3854 case IDENT:
3855 if (!vim_isIDc(c))
3856 return FALSE;
3857 ADVANCE_REGINPUT();
3858 break;
3859
3860 case SIDENT:
3861 if (VIM_ISDIGIT(*reginput) || !vim_isIDc(c))
3862 return FALSE;
3863 ADVANCE_REGINPUT();
3864 break;
3865
3866 case KWORD:
3867 if (!vim_iswordp(reginput))
3868 return FALSE;
3869 ADVANCE_REGINPUT();
3870 break;
3871
3872 case SKWORD:
3873 if (VIM_ISDIGIT(*reginput) || !vim_iswordp(reginput))
3874 return FALSE;
3875 ADVANCE_REGINPUT();
3876 break;
3877
3878 case FNAME:
3879 if (!vim_isfilec(c))
3880 return FALSE;
3881 ADVANCE_REGINPUT();
3882 break;
3883
3884 case SFNAME:
3885 if (VIM_ISDIGIT(*reginput) || !vim_isfilec(c))
3886 return FALSE;
3887 ADVANCE_REGINPUT();
3888 break;
3889
3890 case PRINT:
3891 if (ptr2cells(reginput) != 1)
3892 return FALSE;
3893 ADVANCE_REGINPUT();
3894 break;
3895
3896 case SPRINT:
3897 if (VIM_ISDIGIT(*reginput) || ptr2cells(reginput) != 1)
3898 return FALSE;
3899 ADVANCE_REGINPUT();
3900 break;
3901
3902 case WHITE:
3903 if (!vim_iswhite(c))
3904 return FALSE;
3905 ADVANCE_REGINPUT();
3906 break;
3907
3908 case NWHITE:
3909 if (c == NUL || vim_iswhite(c))
3910 return FALSE;
3911 ADVANCE_REGINPUT();
3912 break;
3913
3914 case DIGIT:
3915 if (!ri_digit(c))
3916 return FALSE;
3917 ADVANCE_REGINPUT();
3918 break;
3919
3920 case NDIGIT:
3921 if (c == NUL || ri_digit(c))
3922 return FALSE;
3923 ADVANCE_REGINPUT();
3924 break;
3925
3926 case HEX:
3927 if (!ri_hex(c))
3928 return FALSE;
3929 ADVANCE_REGINPUT();
3930 break;
3931
3932 case NHEX:
3933 if (c == NUL || ri_hex(c))
3934 return FALSE;
3935 ADVANCE_REGINPUT();
3936 break;
3937
3938 case OCTAL:
3939 if (!ri_octal(c))
3940 return FALSE;
3941 ADVANCE_REGINPUT();
3942 break;
3943
3944 case NOCTAL:
3945 if (c == NUL || ri_octal(c))
3946 return FALSE;
3947 ADVANCE_REGINPUT();
3948 break;
3949
3950 case WORD:
3951 if (!ri_word(c))
3952 return FALSE;
3953 ADVANCE_REGINPUT();
3954 break;
3955
3956 case NWORD:
3957 if (c == NUL || ri_word(c))
3958 return FALSE;
3959 ADVANCE_REGINPUT();
3960 break;
3961
3962 case HEAD:
3963 if (!ri_head(c))
3964 return FALSE;
3965 ADVANCE_REGINPUT();
3966 break;
3967
3968 case NHEAD:
3969 if (c == NUL || ri_head(c))
3970 return FALSE;
3971 ADVANCE_REGINPUT();
3972 break;
3973
3974 case ALPHA:
3975 if (!ri_alpha(c))
3976 return FALSE;
3977 ADVANCE_REGINPUT();
3978 break;
3979
3980 case NALPHA:
3981 if (c == NUL || ri_alpha(c))
3982 return FALSE;
3983 ADVANCE_REGINPUT();
3984 break;
3985
3986 case LOWER:
3987 if (!ri_lower(c))
3988 return FALSE;
3989 ADVANCE_REGINPUT();
3990 break;
3991
3992 case NLOWER:
3993 if (c == NUL || ri_lower(c))
3994 return FALSE;
3995 ADVANCE_REGINPUT();
3996 break;
3997
3998 case UPPER:
3999 if (!ri_upper(c))
4000 return FALSE;
4001 ADVANCE_REGINPUT();
4002 break;
4003
4004 case NUPPER:
4005 if (c == NUL || ri_upper(c))
4006 return FALSE;
4007 ADVANCE_REGINPUT();
4008 break;
4009
4010 case EXACTLY:
4011 {
4012 int len;
4013 char_u *opnd;
4014
4015 opnd = OPERAND(scan);
4016 /* Inline the first byte, for speed. */
4017 if (*opnd != *reginput
4018 && (!ireg_ic || (
4019#ifdef FEAT_MBYTE
4020 !enc_utf8 &&
4021#endif
4022 TOLOWER_LOC(*opnd) != TOLOWER_LOC(*reginput))))
4023 return FALSE;
4024 if (*opnd == NUL)
4025 {
4026 /* match empty string always works; happens when "~" is
4027 * empty. */
4028 }
4029 else if (opnd[1] == NUL
4030#ifdef FEAT_MBYTE
4031 && !(enc_utf8 && ireg_ic)
4032#endif
4033 )
4034 ++reginput; /* matched a single char */
4035 else
4036 {
4037 len = (int)STRLEN(opnd);
4038 /* Need to match first byte again for multi-byte. */
4039 if (cstrncmp(opnd, reginput, &len) != 0)
4040 return FALSE;
4041#ifdef FEAT_MBYTE
4042 /* Check for following composing character. */
4043 if (enc_utf8 && UTF_COMPOSINGLIKE(reginput, reginput + len))
4044 {
4045 /* raaron: This code makes a composing character get
4046 * ignored, which is the correct behavior (sometimes)
4047 * for voweled Hebrew texts. */
4048 if (!ireg_icombine)
4049 return FALSE;
4050 }
4051 else
4052#endif
4053 reginput += len;
4054 }
4055 }
4056 break;
4057
4058 case ANYOF:
4059 case ANYBUT:
4060 if (c == NUL)
4061 return FALSE;
4062 if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
4063 return FALSE;
4064 ADVANCE_REGINPUT();
4065 break;
4066
4067#ifdef FEAT_MBYTE
4068 case MULTIBYTECODE:
4069 if (has_mbyte)
4070 {
4071 int i, len;
4072 char_u *opnd;
4073
4074 opnd = OPERAND(scan);
4075 /* Safety check (just in case 'encoding' was changed since
4076 * compiling the program). */
4077 if ((len = (*mb_ptr2len_check)(opnd)) < 2)
4078 return FALSE;
4079 for (i = 0; i < len; ++i)
4080 if (opnd[i] != reginput[i])
4081 return FALSE;
4082 reginput += len;
4083 }
4084 else
4085 return FALSE;
4086 break;
4087#endif
4088
4089 case NOTHING:
4090 break;
4091
4092 case BACK:
Bram Moolenaardf177f62005-02-22 08:39:57 +00004093 /* When we run into BACK without matching something non-empty, we
4094 * fail. */
4095 if (startp != NULL && reg_save_equal(startp))
4096 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 break;
4098
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004099 case BACKP:
4100 break;
4101
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 case MOPEN + 0: /* Match start: \zs */
4103 case MOPEN + 1: /* \( */
4104 case MOPEN + 2:
4105 case MOPEN + 3:
4106 case MOPEN + 4:
4107 case MOPEN + 5:
4108 case MOPEN + 6:
4109 case MOPEN + 7:
4110 case MOPEN + 8:
4111 case MOPEN + 9:
4112 {
4113 int no;
4114 save_se_T save;
4115
4116 no = op - MOPEN;
4117 cleanup_subexpr();
4118 save_se(&save, &reg_startpos[no], &reg_startp[no]);
4119
Bram Moolenaardf177f62005-02-22 08:39:57 +00004120 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 return TRUE;
4122
4123 restore_se(&save, &reg_startpos[no], &reg_startp[no]);
4124 return FALSE;
4125 }
4126 /* break; Not Reached */
4127
4128 case NOPEN: /* \%( */
4129 case NCLOSE: /* \) after \%( */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004130 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 return TRUE;
4132 return FALSE;
4133 /* break; Not Reached */
4134
4135#ifdef FEAT_SYN_HL
4136 case ZOPEN + 1:
4137 case ZOPEN + 2:
4138 case ZOPEN + 3:
4139 case ZOPEN + 4:
4140 case ZOPEN + 5:
4141 case ZOPEN + 6:
4142 case ZOPEN + 7:
4143 case ZOPEN + 8:
4144 case ZOPEN + 9:
4145 {
4146 int no;
4147 save_se_T save;
4148
4149 no = op - ZOPEN;
4150 cleanup_zsubexpr();
4151 save_se(&save, &reg_startzpos[no], &reg_startzp[no]);
4152
Bram Moolenaardf177f62005-02-22 08:39:57 +00004153 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 return TRUE;
4155
4156 restore_se(&save, &reg_startzpos[no], &reg_startzp[no]);
4157 return FALSE;
4158 }
4159 /* break; Not Reached */
4160#endif
4161
4162 case MCLOSE + 0: /* Match end: \ze */
4163 case MCLOSE + 1: /* \) */
4164 case MCLOSE + 2:
4165 case MCLOSE + 3:
4166 case MCLOSE + 4:
4167 case MCLOSE + 5:
4168 case MCLOSE + 6:
4169 case MCLOSE + 7:
4170 case MCLOSE + 8:
4171 case MCLOSE + 9:
4172 {
4173 int no;
4174 save_se_T save;
4175
4176 no = op - MCLOSE;
4177 cleanup_subexpr();
4178 save_se(&save, &reg_endpos[no], &reg_endp[no]);
4179
Bram Moolenaardf177f62005-02-22 08:39:57 +00004180 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 return TRUE;
4182
4183 restore_se(&save, &reg_endpos[no], &reg_endp[no]);
4184 return FALSE;
4185 }
4186 /* break; Not Reached */
4187
4188#ifdef FEAT_SYN_HL
4189 case ZCLOSE + 1: /* \) after \z( */
4190 case ZCLOSE + 2:
4191 case ZCLOSE + 3:
4192 case ZCLOSE + 4:
4193 case ZCLOSE + 5:
4194 case ZCLOSE + 6:
4195 case ZCLOSE + 7:
4196 case ZCLOSE + 8:
4197 case ZCLOSE + 9:
4198 {
4199 int no;
4200 save_se_T save;
4201
4202 no = op - ZCLOSE;
4203 cleanup_zsubexpr();
4204 save_se(&save, &reg_endzpos[no], &reg_endzp[no]);
4205
Bram Moolenaardf177f62005-02-22 08:39:57 +00004206 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 return TRUE;
4208
4209 restore_se(&save, &reg_endzpos[no], &reg_endzp[no]);
4210 return FALSE;
4211 }
4212 /* break; Not Reached */
4213#endif
4214
4215 case BACKREF + 1:
4216 case BACKREF + 2:
4217 case BACKREF + 3:
4218 case BACKREF + 4:
4219 case BACKREF + 5:
4220 case BACKREF + 6:
4221 case BACKREF + 7:
4222 case BACKREF + 8:
4223 case BACKREF + 9:
4224 {
4225 int no;
4226 int len;
4227 linenr_T clnum;
4228 colnr_T ccol;
4229 char_u *p;
4230
4231 no = op - BACKREF;
4232 cleanup_subexpr();
4233 if (!REG_MULTI) /* Single-line regexp */
4234 {
4235 if (reg_endp[no] == NULL)
4236 {
4237 /* Backref was not set: Match an empty string. */
4238 len = 0;
4239 }
4240 else
4241 {
4242 /* Compare current input with back-ref in the same
4243 * line. */
4244 len = (int)(reg_endp[no] - reg_startp[no]);
4245 if (cstrncmp(reg_startp[no], reginput, &len) != 0)
4246 return FALSE;
4247 }
4248 }
4249 else /* Multi-line regexp */
4250 {
4251 if (reg_endpos[no].lnum < 0)
4252 {
4253 /* Backref was not set: Match an empty string. */
4254 len = 0;
4255 }
4256 else
4257 {
4258 if (reg_startpos[no].lnum == reglnum
4259 && reg_endpos[no].lnum == reglnum)
4260 {
4261 /* Compare back-ref within the current line. */
4262 len = reg_endpos[no].col - reg_startpos[no].col;
4263 if (cstrncmp(regline + reg_startpos[no].col,
4264 reginput, &len) != 0)
4265 return FALSE;
4266 }
4267 else
4268 {
4269 /* Messy situation: Need to compare between two
4270 * lines. */
4271 ccol = reg_startpos[no].col;
4272 clnum = reg_startpos[no].lnum;
4273 for (;;)
4274 {
4275 /* Since getting one line may invalidate
4276 * the other, need to make copy. Slow! */
4277 if (regline != reg_tofree)
4278 {
4279 len = (int)STRLEN(regline);
4280 if (reg_tofree == NULL
4281 || len >= (int)reg_tofreelen)
4282 {
4283 len += 50; /* get some extra */
4284 vim_free(reg_tofree);
4285 reg_tofree = alloc(len);
4286 if (reg_tofree == NULL)
4287 return FALSE; /* out of memory! */
4288 reg_tofreelen = len;
4289 }
4290 STRCPY(reg_tofree, regline);
4291 reginput = reg_tofree
4292 + (reginput - regline);
4293 regline = reg_tofree;
4294 }
4295
4296 /* Get the line to compare with. */
4297 p = reg_getline(clnum);
4298 if (clnum == reg_endpos[no].lnum)
4299 len = reg_endpos[no].col - ccol;
4300 else
4301 len = (int)STRLEN(p + ccol);
4302
4303 if (cstrncmp(p + ccol, reginput, &len) != 0)
4304 return FALSE; /* doesn't match */
4305 if (clnum == reg_endpos[no].lnum)
4306 break; /* match and at end! */
4307 if (reglnum == reg_maxline)
4308 return FALSE; /* text too short */
4309
4310 /* Advance to next line. */
4311 reg_nextline();
4312 ++clnum;
4313 ccol = 0;
4314 if (got_int || out_of_stack)
4315 return FALSE;
4316 }
4317
4318 /* found a match! Note that regline may now point
4319 * to a copy of the line, that should not matter. */
4320 }
4321 }
4322 }
4323
4324 /* Matched the backref, skip over it. */
4325 reginput += len;
4326 }
4327 break;
4328
4329#ifdef FEAT_SYN_HL
4330 case ZREF + 1:
4331 case ZREF + 2:
4332 case ZREF + 3:
4333 case ZREF + 4:
4334 case ZREF + 5:
4335 case ZREF + 6:
4336 case ZREF + 7:
4337 case ZREF + 8:
4338 case ZREF + 9:
4339 {
4340 int no;
4341 int len;
4342
4343 cleanup_zsubexpr();
4344 no = op - ZREF;
4345 if (re_extmatch_in != NULL
4346 && re_extmatch_in->matches[no] != NULL)
4347 {
4348 len = (int)STRLEN(re_extmatch_in->matches[no]);
4349 if (cstrncmp(re_extmatch_in->matches[no],
4350 reginput, &len) != 0)
4351 return FALSE;
4352 reginput += len;
4353 }
4354 else
4355 {
4356 /* Backref was not set: Match an empty string. */
4357 }
4358 }
4359 break;
4360#endif
4361
4362 case BRANCH:
4363 {
4364 if (OP(next) != BRANCH) /* No choice. */
4365 next = OPERAND(scan); /* Avoid recursion. */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004366 else if (startp != NULL && OP(OPERAND(scan)) == BACKP
4367 && reg_save_equal(startp))
4368 /* \+ with something empty before it */
4369 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 else
4371 {
4372 regsave_T save;
4373
4374 do
4375 {
4376 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004377 if (regmatch(OPERAND(scan), &save))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 return TRUE;
4379 reg_restore(&save);
4380 scan = regnext(scan);
4381 } while (scan != NULL && OP(scan) == BRANCH);
4382 return FALSE;
4383 /* NOTREACHED */
4384 }
4385 }
4386 break;
4387
4388 case BRACE_LIMITS:
4389 {
4390 int no;
4391
4392 if (OP(next) == BRACE_SIMPLE)
4393 {
4394 bl_minval = OPERAND_MIN(scan);
4395 bl_maxval = OPERAND_MAX(scan);
4396 }
4397 else if (OP(next) >= BRACE_COMPLEX
4398 && OP(next) < BRACE_COMPLEX + 10)
4399 {
4400 no = OP(next) - BRACE_COMPLEX;
4401 brace_min[no] = OPERAND_MIN(scan);
4402 brace_max[no] = OPERAND_MAX(scan);
4403 brace_count[no] = 0;
4404 }
4405 else
4406 {
4407 EMSG(_(e_internal)); /* Shouldn't happen */
4408 return FALSE;
4409 }
4410 }
4411 break;
4412
4413 case BRACE_COMPLEX + 0:
4414 case BRACE_COMPLEX + 1:
4415 case BRACE_COMPLEX + 2:
4416 case BRACE_COMPLEX + 3:
4417 case BRACE_COMPLEX + 4:
4418 case BRACE_COMPLEX + 5:
4419 case BRACE_COMPLEX + 6:
4420 case BRACE_COMPLEX + 7:
4421 case BRACE_COMPLEX + 8:
4422 case BRACE_COMPLEX + 9:
4423 {
4424 int no;
4425 regsave_T save;
4426
4427 no = op - BRACE_COMPLEX;
4428 ++brace_count[no];
4429
4430 /* If not matched enough times yet, try one more */
4431 if (brace_count[no] <= (brace_min[no] <= brace_max[no]
4432 ? brace_min[no] : brace_max[no]))
4433 {
4434 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004435 if (regmatch(OPERAND(scan), &save))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 return TRUE;
4437 reg_restore(&save);
4438 --brace_count[no]; /* failed, decrement match count */
4439 return FALSE;
4440 }
4441
4442 /* If matched enough times, may try matching some more */
4443 if (brace_min[no] <= brace_max[no])
4444 {
4445 /* Range is the normal way around, use longest match */
4446 if (brace_count[no] <= brace_max[no])
4447 {
4448 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004449 if (regmatch(OPERAND(scan), &save))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 return TRUE; /* matched some more times */
4451 reg_restore(&save);
4452 --brace_count[no]; /* matched just enough times */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004453 /* { continue with the items after \{} */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 }
4455 }
4456 else
4457 {
4458 /* Range is backwards, use shortest match first */
4459 if (brace_count[no] <= brace_min[no])
4460 {
4461 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004462 if (regmatch(next, &save))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 return TRUE;
4464 reg_restore(&save);
4465 next = OPERAND(scan);
4466 /* must try to match one more item */
4467 }
4468 }
4469 }
4470 break;
4471
4472 case BRACE_SIMPLE:
4473 case STAR:
4474 case PLUS:
4475 {
4476 int nextb; /* next byte */
4477 int nextb_ic; /* next byte reverse case */
4478 long count;
4479 regsave_T save;
4480 long minval;
4481 long maxval;
4482
4483 /*
4484 * Lookahead to avoid useless match attempts when we know
4485 * what character comes next.
4486 */
4487 if (OP(next) == EXACTLY)
4488 {
4489 nextb = *OPERAND(next);
4490 if (ireg_ic)
4491 {
4492 if (isupper(nextb))
4493 nextb_ic = TOLOWER_LOC(nextb);
4494 else
4495 nextb_ic = TOUPPER_LOC(nextb);
4496 }
4497 else
4498 nextb_ic = nextb;
4499 }
4500 else
4501 {
4502 nextb = NUL;
4503 nextb_ic = NUL;
4504 }
4505 if (op != BRACE_SIMPLE)
4506 {
4507 minval = (op == STAR) ? 0 : 1;
4508 maxval = MAX_LIMIT;
4509 }
4510 else
4511 {
4512 minval = bl_minval;
4513 maxval = bl_maxval;
4514 }
4515
4516 /*
4517 * When maxval > minval, try matching as much as possible, up
4518 * to maxval. When maxval < minval, try matching at least the
4519 * minimal number (since the range is backwards, that's also
4520 * maxval!).
4521 */
4522 count = regrepeat(OPERAND(scan), maxval);
4523 if (got_int)
4524 return FALSE;
4525 if (minval <= maxval)
4526 {
4527 /* Range is the normal way around, use longest match */
4528 while (count >= minval)
4529 {
4530 /* If it could match, try it. */
4531 if (nextb == NUL || *reginput == nextb
4532 || *reginput == nextb_ic)
4533 {
4534 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004535 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004536 return TRUE;
4537 reg_restore(&save);
4538 }
4539 /* Couldn't or didn't match -- back up one char. */
4540 if (--count < minval)
4541 break;
4542 if (reginput == regline)
4543 {
4544 /* backup to last char of previous line */
4545 --reglnum;
4546 regline = reg_getline(reglnum);
4547 /* Just in case regrepeat() didn't count right. */
4548 if (regline == NULL)
4549 return FALSE;
4550 reginput = regline + STRLEN(regline);
4551 fast_breakcheck();
4552 if (got_int || out_of_stack)
4553 return FALSE;
4554 }
4555 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004556 mb_ptr_back(regline, reginput);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 }
4558 }
4559 else
4560 {
4561 /* Range is backwards, use shortest match first.
4562 * Careful: maxval and minval are exchanged! */
4563 if (count < maxval)
4564 return FALSE;
4565 for (;;)
4566 {
4567 /* If it could work, try it. */
4568 if (nextb == NUL || *reginput == nextb
4569 || *reginput == nextb_ic)
4570 {
4571 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004572 if (regmatch(next, &save))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573 return TRUE;
4574 reg_restore(&save);
4575 }
4576 /* Couldn't or didn't match: try advancing one char. */
4577 if (count == minval
4578 || regrepeat(OPERAND(scan), 1L) == 0)
4579 break;
4580 ++count;
4581 if (got_int || out_of_stack)
4582 return FALSE;
4583 }
4584 }
4585 return FALSE;
4586 }
4587 /* break; Not Reached */
4588
4589 case NOMATCH:
4590 {
4591 regsave_T save;
4592
4593 /* If the operand matches, we fail. Otherwise backup and
4594 * continue with the next item. */
4595 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004596 if (regmatch(OPERAND(scan), startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597 return FALSE;
4598 reg_restore(&save);
4599 }
4600 break;
4601
4602 case MATCH:
4603 case SUBPAT:
4604 {
4605 regsave_T save;
4606
4607 /* If the operand doesn't match, we fail. Otherwise backup
4608 * and continue with the next item. */
4609 reg_save(&save);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004610 if (!regmatch(OPERAND(scan), startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 return FALSE;
4612 if (op == MATCH) /* zero-width */
4613 reg_restore(&save);
4614 }
4615 break;
4616
4617 case BEHIND:
4618 case NOBEHIND:
4619 {
4620 regsave_T save_after, save_start;
4621 regsave_T save_behind_pos;
4622 int needmatch = (op == BEHIND);
4623
4624 /*
4625 * Look back in the input of the operand matches or not. This
4626 * must be done at every position in the input and checking if
4627 * the match ends at the current position.
4628 * First check if the next item matches, that's probably
4629 * faster.
4630 */
4631 reg_save(&save_start);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004632 if (regmatch(next, startp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633 {
4634 /* save the position after the found match for next */
4635 reg_save(&save_after);
4636
4637 /* start looking for a match with operand at the current
4638 * postion. Go back one character until we find the
4639 * result, hitting the start of the line or the previous
4640 * line (for multi-line matching).
4641 * Set behind_pos to where the match should end, BHPOS
4642 * will match it. */
4643 save_behind_pos = behind_pos;
4644 behind_pos = save_start;
4645 for (;;)
4646 {
4647 reg_restore(&save_start);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004648 if (regmatch(OPERAND(scan), startp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 && reg_save_equal(&behind_pos))
4650 {
4651 behind_pos = save_behind_pos;
4652 /* found a match that ends where "next" started */
4653 if (needmatch)
4654 {
4655 reg_restore(&save_after);
4656 return TRUE;
4657 }
4658 return FALSE;
4659 }
4660 /*
4661 * No match: Go back one character. May go to
4662 * previous line once.
4663 */
4664 if (REG_MULTI)
4665 {
4666 if (save_start.rs_u.pos.col == 0)
4667 {
4668 if (save_start.rs_u.pos.lnum
4669 < behind_pos.rs_u.pos.lnum
4670 || reg_getline(
4671 --save_start.rs_u.pos.lnum) == NULL)
4672 break;
4673 reg_restore(&save_start);
4674 save_start.rs_u.pos.col =
4675 (colnr_T)STRLEN(regline);
4676 }
4677 else
4678 --save_start.rs_u.pos.col;
4679 }
4680 else
4681 {
4682 if (save_start.rs_u.ptr == regline)
4683 break;
4684 --save_start.rs_u.ptr;
4685 }
4686 }
4687
4688 /* NOBEHIND succeeds when no match was found */
4689 behind_pos = save_behind_pos;
4690 if (!needmatch)
4691 {
4692 reg_restore(&save_after);
4693 return TRUE;
4694 }
4695 }
4696 return FALSE;
4697 }
4698
4699 case BHPOS:
4700 if (REG_MULTI)
4701 {
4702 if (behind_pos.rs_u.pos.col != (colnr_T)(reginput - regline)
4703 || behind_pos.rs_u.pos.lnum != reglnum)
4704 return FALSE;
4705 }
4706 else if (behind_pos.rs_u.ptr != reginput)
4707 return FALSE;
4708 break;
4709
4710 case NEWL:
4711 if ((c != NUL || reglnum == reg_maxline)
4712 && (c != '\n' || !reg_line_lbr))
4713 return FALSE;
4714 if (reg_line_lbr)
4715 ADVANCE_REGINPUT();
4716 else
4717 reg_nextline();
4718 break;
4719
4720 case END:
4721 return TRUE; /* Success! */
4722
4723 default:
4724 EMSG(_(e_re_corr));
4725#ifdef DEBUG
4726 printf("Illegal op code %d\n", op);
4727#endif
4728 return FALSE;
4729 }
4730 }
4731
4732 scan = next;
4733 }
4734
4735 /*
4736 * We get here only if there's trouble -- normally "case END" is the
4737 * terminating point.
4738 */
4739 EMSG(_(e_re_corr));
4740#ifdef DEBUG
4741 printf("Premature EOL\n");
4742#endif
4743 return FALSE;
4744}
4745
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746/*
4747 * regrepeat - repeatedly match something simple, return how many.
4748 * Advances reginput (and reglnum) to just after the matched chars.
4749 */
4750 static int
4751regrepeat(p, maxcount)
4752 char_u *p;
4753 long maxcount; /* maximum number of matches allowed */
4754{
4755 long count = 0;
4756 char_u *scan;
4757 char_u *opnd;
4758 int mask;
4759 int testval = 0;
4760
4761 scan = reginput; /* Make local copy of reginput for speed. */
4762 opnd = OPERAND(p);
4763 switch (OP(p))
4764 {
4765 case ANY:
4766 case ANY + ADD_NL:
4767 while (count < maxcount)
4768 {
4769 /* Matching anything means we continue until end-of-line (or
4770 * end-of-file for ANY + ADD_NL), only limited by maxcount. */
4771 while (*scan != NUL && count < maxcount)
4772 {
4773 ++count;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004774 mb_ptr_adv(scan);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775 }
4776 if (!WITH_NL(OP(p)) || reglnum == reg_maxline || count == maxcount)
4777 break;
4778 ++count; /* count the line-break */
4779 reg_nextline();
4780 scan = reginput;
4781 if (got_int)
4782 break;
4783 }
4784 break;
4785
4786 case IDENT:
4787 case IDENT + ADD_NL:
4788 testval = TRUE;
4789 /*FALLTHROUGH*/
4790 case SIDENT:
4791 case SIDENT + ADD_NL:
4792 while (count < maxcount)
4793 {
4794 if (vim_isIDc(*scan) && (testval || !VIM_ISDIGIT(*scan)))
4795 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004796 mb_ptr_adv(scan);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797 }
4798 else if (*scan == NUL)
4799 {
4800 if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
4801 break;
4802 reg_nextline();
4803 scan = reginput;
4804 if (got_int)
4805 break;
4806 }
4807 else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
4808 ++scan;
4809 else
4810 break;
4811 ++count;
4812 }
4813 break;
4814
4815 case KWORD:
4816 case KWORD + ADD_NL:
4817 testval = TRUE;
4818 /*FALLTHROUGH*/
4819 case SKWORD:
4820 case SKWORD + ADD_NL:
4821 while (count < maxcount)
4822 {
4823 if (vim_iswordp(scan) && (testval || !VIM_ISDIGIT(*scan)))
4824 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004825 mb_ptr_adv(scan);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 }
4827 else if (*scan == NUL)
4828 {
4829 if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
4830 break;
4831 reg_nextline();
4832 scan = reginput;
4833 if (got_int)
4834 break;
4835 }
4836 else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
4837 ++scan;
4838 else
4839 break;
4840 ++count;
4841 }
4842 break;
4843
4844 case FNAME:
4845 case FNAME + ADD_NL:
4846 testval = TRUE;
4847 /*FALLTHROUGH*/
4848 case SFNAME:
4849 case SFNAME + ADD_NL:
4850 while (count < maxcount)
4851 {
4852 if (vim_isfilec(*scan) && (testval || !VIM_ISDIGIT(*scan)))
4853 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004854 mb_ptr_adv(scan);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
4856 else if (*scan == NUL)
4857 {
4858 if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
4859 break;
4860 reg_nextline();
4861 scan = reginput;
4862 if (got_int)
4863 break;
4864 }
4865 else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
4866 ++scan;
4867 else
4868 break;
4869 ++count;
4870 }
4871 break;
4872
4873 case PRINT:
4874 case PRINT + ADD_NL:
4875 testval = TRUE;
4876 /*FALLTHROUGH*/
4877 case SPRINT:
4878 case SPRINT + ADD_NL:
4879 while (count < maxcount)
4880 {
4881 if (*scan == NUL)
4882 {
4883 if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
4884 break;
4885 reg_nextline();
4886 scan = reginput;
4887 if (got_int)
4888 break;
4889 }
4890 else if (ptr2cells(scan) == 1 && (testval || !VIM_ISDIGIT(*scan)))
4891 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004892 mb_ptr_adv(scan);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 }
4894 else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
4895 ++scan;
4896 else
4897 break;
4898 ++count;
4899 }
4900 break;
4901
4902 case WHITE:
4903 case WHITE + ADD_NL:
4904 testval = mask = RI_WHITE;
4905do_class:
4906 while (count < maxcount)
4907 {
4908#ifdef FEAT_MBYTE
4909 int l;
4910#endif
4911 if (*scan == NUL)
4912 {
4913 if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
4914 break;
4915 reg_nextline();
4916 scan = reginput;
4917 if (got_int)
4918 break;
4919 }
4920#ifdef FEAT_MBYTE
4921 else if (has_mbyte && (l = (*mb_ptr2len_check)(scan)) > 1)
4922 {
4923 if (testval != 0)
4924 break;
4925 scan += l;
4926 }
4927#endif
4928 else if ((class_tab[*scan] & mask) == testval)
4929 ++scan;
4930 else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
4931 ++scan;
4932 else
4933 break;
4934 ++count;
4935 }
4936 break;
4937
4938 case NWHITE:
4939 case NWHITE + ADD_NL:
4940 mask = RI_WHITE;
4941 goto do_class;
4942 case DIGIT:
4943 case DIGIT + ADD_NL:
4944 testval = mask = RI_DIGIT;
4945 goto do_class;
4946 case NDIGIT:
4947 case NDIGIT + ADD_NL:
4948 mask = RI_DIGIT;
4949 goto do_class;
4950 case HEX:
4951 case HEX + ADD_NL:
4952 testval = mask = RI_HEX;
4953 goto do_class;
4954 case NHEX:
4955 case NHEX + ADD_NL:
4956 mask = RI_HEX;
4957 goto do_class;
4958 case OCTAL:
4959 case OCTAL + ADD_NL:
4960 testval = mask = RI_OCTAL;
4961 goto do_class;
4962 case NOCTAL:
4963 case NOCTAL + ADD_NL:
4964 mask = RI_OCTAL;
4965 goto do_class;
4966 case WORD:
4967 case WORD + ADD_NL:
4968 testval = mask = RI_WORD;
4969 goto do_class;
4970 case NWORD:
4971 case NWORD + ADD_NL:
4972 mask = RI_WORD;
4973 goto do_class;
4974 case HEAD:
4975 case HEAD + ADD_NL:
4976 testval = mask = RI_HEAD;
4977 goto do_class;
4978 case NHEAD:
4979 case NHEAD + ADD_NL:
4980 mask = RI_HEAD;
4981 goto do_class;
4982 case ALPHA:
4983 case ALPHA + ADD_NL:
4984 testval = mask = RI_ALPHA;
4985 goto do_class;
4986 case NALPHA:
4987 case NALPHA + ADD_NL:
4988 mask = RI_ALPHA;
4989 goto do_class;
4990 case LOWER:
4991 case LOWER + ADD_NL:
4992 testval = mask = RI_LOWER;
4993 goto do_class;
4994 case NLOWER:
4995 case NLOWER + ADD_NL:
4996 mask = RI_LOWER;
4997 goto do_class;
4998 case UPPER:
4999 case UPPER + ADD_NL:
5000 testval = mask = RI_UPPER;
5001 goto do_class;
5002 case NUPPER:
5003 case NUPPER + ADD_NL:
5004 mask = RI_UPPER;
5005 goto do_class;
5006
5007 case EXACTLY:
5008 {
5009 int cu, cl;
5010
5011 /* This doesn't do a multi-byte character, because a MULTIBYTECODE
5012 * would have been used for it. */
5013 if (ireg_ic)
5014 {
5015 cu = TOUPPER_LOC(*opnd);
5016 cl = TOLOWER_LOC(*opnd);
5017 while (count < maxcount && (*scan == cu || *scan == cl))
5018 {
5019 count++;
5020 scan++;
5021 }
5022 }
5023 else
5024 {
5025 cu = *opnd;
5026 while (count < maxcount && *scan == cu)
5027 {
5028 count++;
5029 scan++;
5030 }
5031 }
5032 break;
5033 }
5034
5035#ifdef FEAT_MBYTE
5036 case MULTIBYTECODE:
5037 {
5038 int i, len, cf = 0;
5039
5040 /* Safety check (just in case 'encoding' was changed since
5041 * compiling the program). */
5042 if ((len = (*mb_ptr2len_check)(opnd)) > 1)
5043 {
5044 if (ireg_ic && enc_utf8)
5045 cf = utf_fold(utf_ptr2char(opnd));
5046 while (count < maxcount)
5047 {
5048 for (i = 0; i < len; ++i)
5049 if (opnd[i] != scan[i])
5050 break;
5051 if (i < len && (!ireg_ic || !enc_utf8
5052 || utf_fold(utf_ptr2char(scan)) != cf))
5053 break;
5054 scan += len;
5055 ++count;
5056 }
5057 }
5058 }
5059 break;
5060#endif
5061
5062 case ANYOF:
5063 case ANYOF + ADD_NL:
5064 testval = TRUE;
5065 /*FALLTHROUGH*/
5066
5067 case ANYBUT:
5068 case ANYBUT + ADD_NL:
5069 while (count < maxcount)
5070 {
5071#ifdef FEAT_MBYTE
5072 int len;
5073#endif
5074 if (*scan == NUL)
5075 {
5076 if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
5077 break;
5078 reg_nextline();
5079 scan = reginput;
5080 if (got_int)
5081 break;
5082 }
5083 else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
5084 ++scan;
5085#ifdef FEAT_MBYTE
5086 else if (has_mbyte && (len = (*mb_ptr2len_check)(scan)) > 1)
5087 {
5088 if ((cstrchr(opnd, (*mb_ptr2char)(scan)) == NULL) == testval)
5089 break;
5090 scan += len;
5091 }
5092#endif
5093 else
5094 {
5095 if ((cstrchr(opnd, *scan) == NULL) == testval)
5096 break;
5097 ++scan;
5098 }
5099 ++count;
5100 }
5101 break;
5102
5103 case NEWL:
5104 while (count < maxcount
5105 && ((*scan == NUL && reglnum < reg_maxline)
5106 || (*scan == '\n' && reg_line_lbr)))
5107 {
5108 count++;
5109 if (reg_line_lbr)
5110 ADVANCE_REGINPUT();
5111 else
5112 reg_nextline();
5113 scan = reginput;
5114 if (got_int)
5115 break;
5116 }
5117 break;
5118
5119 default: /* Oh dear. Called inappropriately. */
5120 EMSG(_(e_re_corr));
5121#ifdef DEBUG
5122 printf("Called regrepeat with op code %d\n", OP(p));
5123#endif
5124 break;
5125 }
5126
5127 reginput = scan;
5128
5129 return (int)count;
5130}
5131
5132/*
5133 * regnext - dig the "next" pointer out of a node
5134 */
5135 static char_u *
5136regnext(p)
5137 char_u *p;
5138{
5139 int offset;
5140
5141 if (p == JUST_CALC_SIZE)
5142 return NULL;
5143
5144 offset = NEXT(p);
5145 if (offset == 0)
5146 return NULL;
5147
Bram Moolenaar19a09a12005-03-04 23:39:37 +00005148 if (OP(p) == BACK || OP(p) == BACKP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149 return p - offset;
5150 else
5151 return p + offset;
5152}
5153
5154/*
5155 * Check the regexp program for its magic number.
5156 * Return TRUE if it's wrong.
5157 */
5158 static int
5159prog_magic_wrong()
5160{
5161 if (UCHARAT(REG_MULTI
5162 ? reg_mmatch->regprog->program
5163 : reg_match->regprog->program) != REGMAGIC)
5164 {
5165 EMSG(_(e_re_corr));
5166 return TRUE;
5167 }
5168 return FALSE;
5169}
5170
5171/*
5172 * Cleanup the subexpressions, if this wasn't done yet.
5173 * This construction is used to clear the subexpressions only when they are
5174 * used (to increase speed).
5175 */
5176 static void
5177cleanup_subexpr()
5178{
5179 if (need_clear_subexpr)
5180 {
5181 if (REG_MULTI)
5182 {
5183 /* Use 0xff to set lnum to -1 */
5184 vim_memset(reg_startpos, 0xff, sizeof(lpos_T) * NSUBEXP);
5185 vim_memset(reg_endpos, 0xff, sizeof(lpos_T) * NSUBEXP);
5186 }
5187 else
5188 {
5189 vim_memset(reg_startp, 0, sizeof(char_u *) * NSUBEXP);
5190 vim_memset(reg_endp, 0, sizeof(char_u *) * NSUBEXP);
5191 }
5192 need_clear_subexpr = FALSE;
5193 }
5194}
5195
5196#ifdef FEAT_SYN_HL
5197 static void
5198cleanup_zsubexpr()
5199{
5200 if (need_clear_zsubexpr)
5201 {
5202 if (REG_MULTI)
5203 {
5204 /* Use 0xff to set lnum to -1 */
5205 vim_memset(reg_startzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
5206 vim_memset(reg_endzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
5207 }
5208 else
5209 {
5210 vim_memset(reg_startzp, 0, sizeof(char_u *) * NSUBEXP);
5211 vim_memset(reg_endzp, 0, sizeof(char_u *) * NSUBEXP);
5212 }
5213 need_clear_zsubexpr = FALSE;
5214 }
5215}
5216#endif
5217
5218/*
5219 * Advance reglnum, regline and reginput to the next line.
5220 */
5221 static void
5222reg_nextline()
5223{
5224 regline = reg_getline(++reglnum);
5225 reginput = regline;
5226 fast_breakcheck();
5227}
5228
5229/*
5230 * Save the input line and position in a regsave_T.
5231 */
5232 static void
5233reg_save(save)
5234 regsave_T *save;
5235{
5236 if (REG_MULTI)
5237 {
5238 save->rs_u.pos.col = (colnr_T)(reginput - regline);
5239 save->rs_u.pos.lnum = reglnum;
5240 }
5241 else
5242 save->rs_u.ptr = reginput;
5243}
5244
5245/*
5246 * Restore the input line and position from a regsave_T.
5247 */
5248 static void
5249reg_restore(save)
5250 regsave_T *save;
5251{
5252 if (REG_MULTI)
5253 {
5254 if (reglnum != save->rs_u.pos.lnum)
5255 {
5256 /* only call reg_getline() when the line number changed to save
5257 * a bit of time */
5258 reglnum = save->rs_u.pos.lnum;
5259 regline = reg_getline(reglnum);
5260 }
5261 reginput = regline + save->rs_u.pos.col;
5262 }
5263 else
5264 reginput = save->rs_u.ptr;
5265}
5266
5267/*
5268 * Return TRUE if current position is equal to saved position.
5269 */
5270 static int
5271reg_save_equal(save)
5272 regsave_T *save;
5273{
5274 if (REG_MULTI)
5275 return reglnum == save->rs_u.pos.lnum
5276 && reginput == regline + save->rs_u.pos.col;
5277 return reginput == save->rs_u.ptr;
5278}
5279
5280/*
5281 * Tentatively set the sub-expression start to the current position (after
5282 * calling regmatch() they will have changed). Need to save the existing
5283 * values for when there is no match.
5284 * Use se_save() to use pointer (save_se_multi()) or position (save_se_one()),
5285 * depending on REG_MULTI.
5286 */
5287 static void
5288save_se_multi(savep, posp)
5289 save_se_T *savep;
5290 lpos_T *posp;
5291{
5292 savep->se_u.pos = *posp;
5293 posp->lnum = reglnum;
5294 posp->col = (colnr_T)(reginput - regline);
5295}
5296
5297 static void
5298save_se_one(savep, pp)
5299 save_se_T *savep;
5300 char_u **pp;
5301{
5302 savep->se_u.ptr = *pp;
5303 *pp = reginput;
5304}
5305
5306/*
5307 * Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
5308 */
5309 static int
5310re_num_cmp(val, scan)
5311 long_u val;
5312 char_u *scan;
5313{
5314 long_u n = OPERAND_MIN(scan);
5315
5316 if (OPERAND_CMP(scan) == '>')
5317 return val > n;
5318 if (OPERAND_CMP(scan) == '<')
5319 return val < n;
5320 return val == n;
5321}
5322
5323
5324#ifdef DEBUG
5325
5326/*
5327 * regdump - dump a regexp onto stdout in vaguely comprehensible form
5328 */
5329 static void
5330regdump(pattern, r)
5331 char_u *pattern;
5332 regprog_T *r;
5333{
5334 char_u *s;
5335 int op = EXACTLY; /* Arbitrary non-END op. */
5336 char_u *next;
5337 char_u *end = NULL;
5338
5339 printf("\r\nregcomp(%s):\r\n", pattern);
5340
5341 s = r->program + 1;
5342 /*
5343 * Loop until we find the END that isn't before a referred next (an END
5344 * can also appear in a NOMATCH operand).
5345 */
5346 while (op != END || s <= end)
5347 {
5348 op = OP(s);
5349 printf("%2d%s", (int)(s - r->program), regprop(s)); /* Where, what. */
5350 next = regnext(s);
5351 if (next == NULL) /* Next ptr. */
5352 printf("(0)");
5353 else
5354 printf("(%d)", (int)((s - r->program) + (next - s)));
5355 if (end < next)
5356 end = next;
5357 if (op == BRACE_LIMITS)
5358 {
5359 /* Two short ints */
5360 printf(" minval %ld, maxval %ld", OPERAND_MIN(s), OPERAND_MAX(s));
5361 s += 8;
5362 }
5363 s += 3;
5364 if (op == ANYOF || op == ANYOF + ADD_NL
5365 || op == ANYBUT || op == ANYBUT + ADD_NL
5366 || op == EXACTLY)
5367 {
5368 /* Literal string, where present. */
5369 while (*s != NUL)
5370 printf("%c", *s++);
5371 s++;
5372 }
5373 printf("\r\n");
5374 }
5375
5376 /* Header fields of interest. */
5377 if (r->regstart != NUL)
5378 printf("start `%s' 0x%x; ", r->regstart < 256
5379 ? (char *)transchar(r->regstart)
5380 : "multibyte", r->regstart);
5381 if (r->reganch)
5382 printf("anchored; ");
5383 if (r->regmust != NULL)
5384 printf("must have \"%s\"", r->regmust);
5385 printf("\r\n");
5386}
5387
5388/*
5389 * regprop - printable representation of opcode
5390 */
5391 static char_u *
5392regprop(op)
5393 char_u *op;
5394{
5395 char_u *p;
5396 static char_u buf[50];
5397
5398 (void) strcpy(buf, ":");
5399
5400 switch (OP(op))
5401 {
5402 case BOL:
5403 p = "BOL";
5404 break;
5405 case EOL:
5406 p = "EOL";
5407 break;
5408 case RE_BOF:
5409 p = "BOF";
5410 break;
5411 case RE_EOF:
5412 p = "EOF";
5413 break;
5414 case CURSOR:
5415 p = "CURSOR";
5416 break;
5417 case RE_LNUM:
5418 p = "RE_LNUM";
5419 break;
5420 case RE_COL:
5421 p = "RE_COL";
5422 break;
5423 case RE_VCOL:
5424 p = "RE_VCOL";
5425 break;
5426 case BOW:
5427 p = "BOW";
5428 break;
5429 case EOW:
5430 p = "EOW";
5431 break;
5432 case ANY:
5433 p = "ANY";
5434 break;
5435 case ANY + ADD_NL:
5436 p = "ANY+NL";
5437 break;
5438 case ANYOF:
5439 p = "ANYOF";
5440 break;
5441 case ANYOF + ADD_NL:
5442 p = "ANYOF+NL";
5443 break;
5444 case ANYBUT:
5445 p = "ANYBUT";
5446 break;
5447 case ANYBUT + ADD_NL:
5448 p = "ANYBUT+NL";
5449 break;
5450 case IDENT:
5451 p = "IDENT";
5452 break;
5453 case IDENT + ADD_NL:
5454 p = "IDENT+NL";
5455 break;
5456 case SIDENT:
5457 p = "SIDENT";
5458 break;
5459 case SIDENT + ADD_NL:
5460 p = "SIDENT+NL";
5461 break;
5462 case KWORD:
5463 p = "KWORD";
5464 break;
5465 case KWORD + ADD_NL:
5466 p = "KWORD+NL";
5467 break;
5468 case SKWORD:
5469 p = "SKWORD";
5470 break;
5471 case SKWORD + ADD_NL:
5472 p = "SKWORD+NL";
5473 break;
5474 case FNAME:
5475 p = "FNAME";
5476 break;
5477 case FNAME + ADD_NL:
5478 p = "FNAME+NL";
5479 break;
5480 case SFNAME:
5481 p = "SFNAME";
5482 break;
5483 case SFNAME + ADD_NL:
5484 p = "SFNAME+NL";
5485 break;
5486 case PRINT:
5487 p = "PRINT";
5488 break;
5489 case PRINT + ADD_NL:
5490 p = "PRINT+NL";
5491 break;
5492 case SPRINT:
5493 p = "SPRINT";
5494 break;
5495 case SPRINT + ADD_NL:
5496 p = "SPRINT+NL";
5497 break;
5498 case WHITE:
5499 p = "WHITE";
5500 break;
5501 case WHITE + ADD_NL:
5502 p = "WHITE+NL";
5503 break;
5504 case NWHITE:
5505 p = "NWHITE";
5506 break;
5507 case NWHITE + ADD_NL:
5508 p = "NWHITE+NL";
5509 break;
5510 case DIGIT:
5511 p = "DIGIT";
5512 break;
5513 case DIGIT + ADD_NL:
5514 p = "DIGIT+NL";
5515 break;
5516 case NDIGIT:
5517 p = "NDIGIT";
5518 break;
5519 case NDIGIT + ADD_NL:
5520 p = "NDIGIT+NL";
5521 break;
5522 case HEX:
5523 p = "HEX";
5524 break;
5525 case HEX + ADD_NL:
5526 p = "HEX+NL";
5527 break;
5528 case NHEX:
5529 p = "NHEX";
5530 break;
5531 case NHEX + ADD_NL:
5532 p = "NHEX+NL";
5533 break;
5534 case OCTAL:
5535 p = "OCTAL";
5536 break;
5537 case OCTAL + ADD_NL:
5538 p = "OCTAL+NL";
5539 break;
5540 case NOCTAL:
5541 p = "NOCTAL";
5542 break;
5543 case NOCTAL + ADD_NL:
5544 p = "NOCTAL+NL";
5545 break;
5546 case WORD:
5547 p = "WORD";
5548 break;
5549 case WORD + ADD_NL:
5550 p = "WORD+NL";
5551 break;
5552 case NWORD:
5553 p = "NWORD";
5554 break;
5555 case NWORD + ADD_NL:
5556 p = "NWORD+NL";
5557 break;
5558 case HEAD:
5559 p = "HEAD";
5560 break;
5561 case HEAD + ADD_NL:
5562 p = "HEAD+NL";
5563 break;
5564 case NHEAD:
5565 p = "NHEAD";
5566 break;
5567 case NHEAD + ADD_NL:
5568 p = "NHEAD+NL";
5569 break;
5570 case ALPHA:
5571 p = "ALPHA";
5572 break;
5573 case ALPHA + ADD_NL:
5574 p = "ALPHA+NL";
5575 break;
5576 case NALPHA:
5577 p = "NALPHA";
5578 break;
5579 case NALPHA + ADD_NL:
5580 p = "NALPHA+NL";
5581 break;
5582 case LOWER:
5583 p = "LOWER";
5584 break;
5585 case LOWER + ADD_NL:
5586 p = "LOWER+NL";
5587 break;
5588 case NLOWER:
5589 p = "NLOWER";
5590 break;
5591 case NLOWER + ADD_NL:
5592 p = "NLOWER+NL";
5593 break;
5594 case UPPER:
5595 p = "UPPER";
5596 break;
5597 case UPPER + ADD_NL:
5598 p = "UPPER+NL";
5599 break;
5600 case NUPPER:
5601 p = "NUPPER";
5602 break;
5603 case NUPPER + ADD_NL:
5604 p = "NUPPER+NL";
5605 break;
5606 case BRANCH:
5607 p = "BRANCH";
5608 break;
5609 case EXACTLY:
5610 p = "EXACTLY";
5611 break;
5612 case NOTHING:
5613 p = "NOTHING";
5614 break;
5615 case BACK:
5616 p = "BACK";
5617 break;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00005618 case BACKP:
5619 p = "BACKP";
5620 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 case END:
5622 p = "END";
5623 break;
5624 case MOPEN + 0:
5625 p = "MATCH START";
5626 break;
5627 case MOPEN + 1:
5628 case MOPEN + 2:
5629 case MOPEN + 3:
5630 case MOPEN + 4:
5631 case MOPEN + 5:
5632 case MOPEN + 6:
5633 case MOPEN + 7:
5634 case MOPEN + 8:
5635 case MOPEN + 9:
5636 sprintf(buf + STRLEN(buf), "MOPEN%d", OP(op) - MOPEN);
5637 p = NULL;
5638 break;
5639 case MCLOSE + 0:
5640 p = "MATCH END";
5641 break;
5642 case MCLOSE + 1:
5643 case MCLOSE + 2:
5644 case MCLOSE + 3:
5645 case MCLOSE + 4:
5646 case MCLOSE + 5:
5647 case MCLOSE + 6:
5648 case MCLOSE + 7:
5649 case MCLOSE + 8:
5650 case MCLOSE + 9:
5651 sprintf(buf + STRLEN(buf), "MCLOSE%d", OP(op) - MCLOSE);
5652 p = NULL;
5653 break;
5654 case BACKREF + 1:
5655 case BACKREF + 2:
5656 case BACKREF + 3:
5657 case BACKREF + 4:
5658 case BACKREF + 5:
5659 case BACKREF + 6:
5660 case BACKREF + 7:
5661 case BACKREF + 8:
5662 case BACKREF + 9:
5663 sprintf(buf + STRLEN(buf), "BACKREF%d", OP(op) - BACKREF);
5664 p = NULL;
5665 break;
5666 case NOPEN:
5667 p = "NOPEN";
5668 break;
5669 case NCLOSE:
5670 p = "NCLOSE";
5671 break;
5672#ifdef FEAT_SYN_HL
5673 case ZOPEN + 1:
5674 case ZOPEN + 2:
5675 case ZOPEN + 3:
5676 case ZOPEN + 4:
5677 case ZOPEN + 5:
5678 case ZOPEN + 6:
5679 case ZOPEN + 7:
5680 case ZOPEN + 8:
5681 case ZOPEN + 9:
5682 sprintf(buf + STRLEN(buf), "ZOPEN%d", OP(op) - ZOPEN);
5683 p = NULL;
5684 break;
5685 case ZCLOSE + 1:
5686 case ZCLOSE + 2:
5687 case ZCLOSE + 3:
5688 case ZCLOSE + 4:
5689 case ZCLOSE + 5:
5690 case ZCLOSE + 6:
5691 case ZCLOSE + 7:
5692 case ZCLOSE + 8:
5693 case ZCLOSE + 9:
5694 sprintf(buf + STRLEN(buf), "ZCLOSE%d", OP(op) - ZCLOSE);
5695 p = NULL;
5696 break;
5697 case ZREF + 1:
5698 case ZREF + 2:
5699 case ZREF + 3:
5700 case ZREF + 4:
5701 case ZREF + 5:
5702 case ZREF + 6:
5703 case ZREF + 7:
5704 case ZREF + 8:
5705 case ZREF + 9:
5706 sprintf(buf + STRLEN(buf), "ZREF%d", OP(op) - ZREF);
5707 p = NULL;
5708 break;
5709#endif
5710 case STAR:
5711 p = "STAR";
5712 break;
5713 case PLUS:
5714 p = "PLUS";
5715 break;
5716 case NOMATCH:
5717 p = "NOMATCH";
5718 break;
5719 case MATCH:
5720 p = "MATCH";
5721 break;
5722 case BEHIND:
5723 p = "BEHIND";
5724 break;
5725 case NOBEHIND:
5726 p = "NOBEHIND";
5727 break;
5728 case SUBPAT:
5729 p = "SUBPAT";
5730 break;
5731 case BRACE_LIMITS:
5732 p = "BRACE_LIMITS";
5733 break;
5734 case BRACE_SIMPLE:
5735 p = "BRACE_SIMPLE";
5736 break;
5737 case BRACE_COMPLEX + 0:
5738 case BRACE_COMPLEX + 1:
5739 case BRACE_COMPLEX + 2:
5740 case BRACE_COMPLEX + 3:
5741 case BRACE_COMPLEX + 4:
5742 case BRACE_COMPLEX + 5:
5743 case BRACE_COMPLEX + 6:
5744 case BRACE_COMPLEX + 7:
5745 case BRACE_COMPLEX + 8:
5746 case BRACE_COMPLEX + 9:
5747 sprintf(buf + STRLEN(buf), "BRACE_COMPLEX%d", OP(op) - BRACE_COMPLEX);
5748 p = NULL;
5749 break;
5750#ifdef FEAT_MBYTE
5751 case MULTIBYTECODE:
5752 p = "MULTIBYTECODE";
5753 break;
5754#endif
5755 case NEWL:
5756 p = "NEWL";
5757 break;
5758 default:
5759 sprintf(buf + STRLEN(buf), "corrupt %d", OP(op));
5760 p = NULL;
5761 break;
5762 }
5763 if (p != NULL)
5764 (void) strcat(buf, p);
5765 return buf;
5766}
5767#endif
5768
5769#ifdef FEAT_MBYTE
5770static void mb_decompose __ARGS((int c, int *c1, int *c2, int *c3));
5771
5772typedef struct
5773{
5774 int a, b, c;
5775} decomp_T;
5776
5777
5778/* 0xfb20 - 0xfb4f */
5779decomp_T decomp_table[0xfb4f-0xfb20+1] =
5780{
5781 {0x5e2,0,0}, /* 0xfb20 alt ayin */
5782 {0x5d0,0,0}, /* 0xfb21 alt alef */
5783 {0x5d3,0,0}, /* 0xfb22 alt dalet */
5784 {0x5d4,0,0}, /* 0xfb23 alt he */
5785 {0x5db,0,0}, /* 0xfb24 alt kaf */
5786 {0x5dc,0,0}, /* 0xfb25 alt lamed */
5787 {0x5dd,0,0}, /* 0xfb26 alt mem-sofit */
5788 {0x5e8,0,0}, /* 0xfb27 alt resh */
5789 {0x5ea,0,0}, /* 0xfb28 alt tav */
5790 {'+', 0, 0}, /* 0xfb29 alt plus */
5791 {0x5e9, 0x5c1, 0}, /* 0xfb2a shin+shin-dot */
5792 {0x5e9, 0x5c2, 0}, /* 0xfb2b shin+sin-dot */
5793 {0x5e9, 0x5c1, 0x5bc}, /* 0xfb2c shin+shin-dot+dagesh */
5794 {0x5e9, 0x5c2, 0x5bc}, /* 0xfb2d shin+sin-dot+dagesh */
5795 {0x5d0, 0x5b7, 0}, /* 0xfb2e alef+patah */
5796 {0x5d0, 0x5b8, 0}, /* 0xfb2f alef+qamats */
5797 {0x5d0, 0x5b4, 0}, /* 0xfb30 alef+hiriq */
5798 {0x5d1, 0x5bc, 0}, /* 0xfb31 bet+dagesh */
5799 {0x5d2, 0x5bc, 0}, /* 0xfb32 gimel+dagesh */
5800 {0x5d3, 0x5bc, 0}, /* 0xfb33 dalet+dagesh */
5801 {0x5d4, 0x5bc, 0}, /* 0xfb34 he+dagesh */
5802 {0x5d5, 0x5bc, 0}, /* 0xfb35 vav+dagesh */
5803 {0x5d6, 0x5bc, 0}, /* 0xfb36 zayin+dagesh */
5804 {0xfb37, 0, 0}, /* 0xfb37 -- UNUSED */
5805 {0x5d8, 0x5bc, 0}, /* 0xfb38 tet+dagesh */
5806 {0x5d9, 0x5bc, 0}, /* 0xfb39 yud+dagesh */
5807 {0x5da, 0x5bc, 0}, /* 0xfb3a kaf sofit+dagesh */
5808 {0x5db, 0x5bc, 0}, /* 0xfb3b kaf+dagesh */
5809 {0x5dc, 0x5bc, 0}, /* 0xfb3c lamed+dagesh */
5810 {0xfb3d, 0, 0}, /* 0xfb3d -- UNUSED */
5811 {0x5de, 0x5bc, 0}, /* 0xfb3e mem+dagesh */
5812 {0xfb3f, 0, 0}, /* 0xfb3f -- UNUSED */
5813 {0x5e0, 0x5bc, 0}, /* 0xfb40 nun+dagesh */
5814 {0x5e1, 0x5bc, 0}, /* 0xfb41 samech+dagesh */
5815 {0xfb42, 0, 0}, /* 0xfb42 -- UNUSED */
5816 {0x5e3, 0x5bc, 0}, /* 0xfb43 pe sofit+dagesh */
5817 {0x5e4, 0x5bc,0}, /* 0xfb44 pe+dagesh */
5818 {0xfb45, 0, 0}, /* 0xfb45 -- UNUSED */
5819 {0x5e6, 0x5bc, 0}, /* 0xfb46 tsadi+dagesh */
5820 {0x5e7, 0x5bc, 0}, /* 0xfb47 qof+dagesh */
5821 {0x5e8, 0x5bc, 0}, /* 0xfb48 resh+dagesh */
5822 {0x5e9, 0x5bc, 0}, /* 0xfb49 shin+dagesh */
5823 {0x5ea, 0x5bc, 0}, /* 0xfb4a tav+dagesh */
5824 {0x5d5, 0x5b9, 0}, /* 0xfb4b vav+holam */
5825 {0x5d1, 0x5bf, 0}, /* 0xfb4c bet+rafe */
5826 {0x5db, 0x5bf, 0}, /* 0xfb4d kaf+rafe */
5827 {0x5e4, 0x5bf, 0}, /* 0xfb4e pe+rafe */
5828 {0x5d0, 0x5dc, 0} /* 0xfb4f alef-lamed */
5829};
5830
5831 static void
5832mb_decompose(c, c1, c2, c3)
5833 int c, *c1, *c2, *c3;
5834{
5835 decomp_T d;
5836
5837 if (c >= 0x4b20 && c <= 0xfb4f)
5838 {
5839 d = decomp_table[c - 0xfb20];
5840 *c1 = d.a;
5841 *c2 = d.b;
5842 *c3 = d.c;
5843 }
5844 else
5845 {
5846 *c1 = c;
5847 *c2 = *c3 = 0;
5848 }
5849}
5850#endif
5851
5852/*
5853 * Compare two strings, ignore case if ireg_ic set.
5854 * Return 0 if strings match, non-zero otherwise.
5855 * Correct the length "*n" when composing characters are ignored.
5856 */
5857 static int
5858cstrncmp(s1, s2, n)
5859 char_u *s1, *s2;
5860 int *n;
5861{
5862 int result;
5863
5864 if (!ireg_ic)
5865 result = STRNCMP(s1, s2, *n);
5866 else
5867 result = MB_STRNICMP(s1, s2, *n);
5868
5869#ifdef FEAT_MBYTE
5870 /* if it failed and it's utf8 and we want to combineignore: */
5871 if (result != 0 && enc_utf8 && ireg_icombine)
5872 {
5873 char_u *str1, *str2;
5874 int c1, c2, c11, c12;
5875 int ix;
5876 int junk;
5877
5878 /* we have to handle the strcmp ourselves, since it is necessary to
5879 * deal with the composing characters by ignoring them: */
5880 str1 = s1;
5881 str2 = s2;
5882 c1 = c2 = 0;
5883 for (ix = 0; ix < *n; )
5884 {
5885 c1 = mb_ptr2char_adv(&str1);
5886 c2 = mb_ptr2char_adv(&str2);
5887 ix += utf_char2len(c1);
5888
5889 /* decompose the character if necessary, into 'base' characters
5890 * because I don't care about Arabic, I will hard-code the Hebrew
5891 * which I *do* care about! So sue me... */
5892 if (c1 != c2 && (!ireg_ic || utf_fold(c1) != utf_fold(c2)))
5893 {
5894 /* decomposition necessary? */
5895 mb_decompose(c1, &c11, &junk, &junk);
5896 mb_decompose(c2, &c12, &junk, &junk);
5897 c1 = c11;
5898 c2 = c12;
5899 if (c11 != c12 && (!ireg_ic || utf_fold(c11) != utf_fold(c12)))
5900 break;
5901 }
5902 }
5903 result = c2 - c1;
5904 if (result == 0)
5905 *n = (int)(str2 - s2);
5906 }
5907#endif
5908
5909 return result;
5910}
5911
5912/*
5913 * cstrchr: This function is used a lot for simple searches, keep it fast!
5914 */
5915 static char_u *
5916cstrchr(s, c)
5917 char_u *s;
5918 int c;
5919{
5920 char_u *p;
5921 int cc;
5922
5923 if (!ireg_ic
5924#ifdef FEAT_MBYTE
5925 || (!enc_utf8 && mb_char2len(c) > 1)
5926#endif
5927 )
5928 return vim_strchr(s, c);
5929
5930 /* tolower() and toupper() can be slow, comparing twice should be a lot
5931 * faster (esp. when using MS Visual C++!).
5932 * For UTF-8 need to use folded case. */
5933#ifdef FEAT_MBYTE
5934 if (enc_utf8 && c > 0x80)
5935 cc = utf_fold(c);
5936 else
5937#endif
5938 if (isupper(c))
5939 cc = TOLOWER_LOC(c);
5940 else if (islower(c))
5941 cc = TOUPPER_LOC(c);
5942 else
5943 return vim_strchr(s, c);
5944
5945#ifdef FEAT_MBYTE
5946 if (has_mbyte)
5947 {
5948 for (p = s; *p != NUL; p += (*mb_ptr2len_check)(p))
5949 {
5950 if (enc_utf8 && c > 0x80)
5951 {
5952 if (utf_fold(utf_ptr2char(p)) == cc)
5953 return p;
5954 }
5955 else if (*p == c || *p == cc)
5956 return p;
5957 }
5958 }
5959 else
5960#endif
5961 /* Faster version for when there are no multi-byte characters. */
5962 for (p = s; *p != NUL; ++p)
5963 if (*p == c || *p == cc)
5964 return p;
5965
5966 return NULL;
5967}
5968
5969/***************************************************************
5970 * regsub stuff *
5971 ***************************************************************/
5972
5973/* This stuff below really confuses cc on an SGI -- webb */
5974#ifdef __sgi
5975# undef __ARGS
5976# define __ARGS(x) ()
5977#endif
5978
5979/*
5980 * We should define ftpr as a pointer to a function returning a pointer to
5981 * a function returning a pointer to a function ...
5982 * This is impossible, so we declare a pointer to a function returning a
5983 * pointer to a function returning void. This should work for all compilers.
5984 */
5985typedef void (*(*fptr) __ARGS((char_u *, int)))();
5986
5987static fptr do_upper __ARGS((char_u *, int));
5988static fptr do_Upper __ARGS((char_u *, int));
5989static fptr do_lower __ARGS((char_u *, int));
5990static fptr do_Lower __ARGS((char_u *, int));
5991
5992static int vim_regsub_both __ARGS((char_u *source, char_u *dest, int copy, int magic, int backslash));
5993
5994 static fptr
5995do_upper(d, c)
5996 char_u *d;
5997 int c;
5998{
5999 *d = TOUPPER_LOC(c);
6000
6001 return (fptr)NULL;
6002}
6003
6004 static fptr
6005do_Upper(d, c)
6006 char_u *d;
6007 int c;
6008{
6009 *d = TOUPPER_LOC(c);
6010
6011 return (fptr)do_Upper;
6012}
6013
6014 static fptr
6015do_lower(d, c)
6016 char_u *d;
6017 int c;
6018{
6019 *d = TOLOWER_LOC(c);
6020
6021 return (fptr)NULL;
6022}
6023
6024 static fptr
6025do_Lower(d, c)
6026 char_u *d;
6027 int c;
6028{
6029 *d = TOLOWER_LOC(c);
6030
6031 return (fptr)do_Lower;
6032}
6033
6034/*
6035 * regtilde(): Replace tildes in the pattern by the old pattern.
6036 *
6037 * Short explanation of the tilde: It stands for the previous replacement
6038 * pattern. If that previous pattern also contains a ~ we should go back a
6039 * step further... But we insert the previous pattern into the current one
6040 * and remember that.
6041 * This still does not handle the case where "magic" changes. TODO?
6042 *
6043 * The tildes are parsed once before the first call to vim_regsub().
6044 */
6045 char_u *
6046regtilde(source, magic)
6047 char_u *source;
6048 int magic;
6049{
6050 char_u *newsub = source;
6051 char_u *tmpsub;
6052 char_u *p;
6053 int len;
6054 int prevlen;
6055
6056 for (p = newsub; *p; ++p)
6057 {
6058 if ((*p == '~' && magic) || (*p == '\\' && *(p + 1) == '~' && !magic))
6059 {
6060 if (reg_prev_sub != NULL)
6061 {
6062 /* length = len(newsub) - 1 + len(prev_sub) + 1 */
6063 prevlen = (int)STRLEN(reg_prev_sub);
6064 tmpsub = alloc((unsigned)(STRLEN(newsub) + prevlen));
6065 if (tmpsub != NULL)
6066 {
6067 /* copy prefix */
6068 len = (int)(p - newsub); /* not including ~ */
6069 mch_memmove(tmpsub, newsub, (size_t)len);
6070 /* interpretate tilde */
6071 mch_memmove(tmpsub + len, reg_prev_sub, (size_t)prevlen);
6072 /* copy postfix */
6073 if (!magic)
6074 ++p; /* back off \ */
6075 STRCPY(tmpsub + len + prevlen, p + 1);
6076
6077 if (newsub != source) /* already allocated newsub */
6078 vim_free(newsub);
6079 newsub = tmpsub;
6080 p = newsub + len + prevlen;
6081 }
6082 }
6083 else if (magic)
6084 STRCPY(p, p + 1); /* remove '~' */
6085 else
6086 STRCPY(p, p + 2); /* remove '\~' */
6087 --p;
6088 }
6089 else
6090 {
6091 if (*p == '\\' && p[1]) /* skip escaped characters */
6092 ++p;
6093#ifdef FEAT_MBYTE
6094 if (has_mbyte)
6095 p += (*mb_ptr2len_check)(p) - 1;
6096#endif
6097 }
6098 }
6099
6100 vim_free(reg_prev_sub);
6101 if (newsub != source) /* newsub was allocated, just keep it */
6102 reg_prev_sub = newsub;
6103 else /* no ~ found, need to save newsub */
6104 reg_prev_sub = vim_strsave(newsub);
6105 return newsub;
6106}
6107
6108#ifdef FEAT_EVAL
6109static int can_f_submatch = FALSE; /* TRUE when submatch() can be used */
6110
6111/* These pointers are used instead of reg_match and reg_mmatch for
6112 * reg_submatch(). Needed for when the substitution string is an expression
6113 * that contains a call to substitute() and submatch(). */
6114static regmatch_T *submatch_match;
6115static regmmatch_T *submatch_mmatch;
6116#endif
6117
6118#if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
6119/*
6120 * vim_regsub() - perform substitutions after a vim_regexec() or
6121 * vim_regexec_multi() match.
6122 *
6123 * If "copy" is TRUE really copy into "dest".
6124 * If "copy" is FALSE nothing is copied, this is just to find out the length
6125 * of the result.
6126 *
6127 * If "backslash" is TRUE, a backslash will be removed later, need to double
6128 * them to keep them, and insert a backslash before a CR to avoid it being
6129 * replaced with a line break later.
6130 *
6131 * Note: The matched text must not change between the call of
6132 * vim_regexec()/vim_regexec_multi() and vim_regsub()! It would make the back
6133 * references invalid!
6134 *
6135 * Returns the size of the replacement, including terminating NUL.
6136 */
6137 int
6138vim_regsub(rmp, source, dest, copy, magic, backslash)
6139 regmatch_T *rmp;
6140 char_u *source;
6141 char_u *dest;
6142 int copy;
6143 int magic;
6144 int backslash;
6145{
6146 reg_match = rmp;
6147 reg_mmatch = NULL;
6148 reg_maxline = 0;
6149 return vim_regsub_both(source, dest, copy, magic, backslash);
6150}
6151#endif
6152
6153 int
6154vim_regsub_multi(rmp, lnum, source, dest, copy, magic, backslash)
6155 regmmatch_T *rmp;
6156 linenr_T lnum;
6157 char_u *source;
6158 char_u *dest;
6159 int copy;
6160 int magic;
6161 int backslash;
6162{
6163 reg_match = NULL;
6164 reg_mmatch = rmp;
6165 reg_buf = curbuf; /* always works on the current buffer! */
6166 reg_firstlnum = lnum;
6167 reg_maxline = curbuf->b_ml.ml_line_count - lnum;
6168 return vim_regsub_both(source, dest, copy, magic, backslash);
6169}
6170
6171 static int
6172vim_regsub_both(source, dest, copy, magic, backslash)
6173 char_u *source;
6174 char_u *dest;
6175 int copy;
6176 int magic;
6177 int backslash;
6178{
6179 char_u *src;
6180 char_u *dst;
6181 char_u *s;
6182 int c;
6183 int no = -1;
6184 fptr func = (fptr)NULL;
6185 linenr_T clnum = 0; /* init for GCC */
6186 int len = 0; /* init for GCC */
6187#ifdef FEAT_EVAL
6188 static char_u *eval_result = NULL;
6189#endif
6190#ifdef FEAT_MBYTE
6191 int l;
6192#endif
6193
6194
6195 /* Be paranoid... */
6196 if (source == NULL || dest == NULL)
6197 {
6198 EMSG(_(e_null));
6199 return 0;
6200 }
6201 if (prog_magic_wrong())
6202 return 0;
6203 src = source;
6204 dst = dest;
6205
6206 /*
6207 * When the substitute part starts with "\=" evaluate it as an expression.
6208 */
6209 if (source[0] == '\\' && source[1] == '='
6210#ifdef FEAT_EVAL
6211 && !can_f_submatch /* can't do this recursively */
6212#endif
6213 )
6214 {
6215#ifdef FEAT_EVAL
6216 /* To make sure that the length doesn't change between checking the
6217 * length and copying the string, and to speed up things, the
6218 * resulting string is saved from the call with "copy" == FALSE to the
6219 * call with "copy" == TRUE. */
6220 if (copy)
6221 {
6222 if (eval_result != NULL)
6223 {
6224 STRCPY(dest, eval_result);
6225 dst += STRLEN(eval_result);
6226 vim_free(eval_result);
6227 eval_result = NULL;
6228 }
6229 }
6230 else
6231 {
6232 linenr_T save_reg_maxline;
6233 win_T *save_reg_win;
6234 int save_ireg_ic;
6235
6236 vim_free(eval_result);
6237
6238 /* The expression may contain substitute(), which calls us
6239 * recursively. Make sure submatch() gets the text from the first
6240 * level. Don't need to save "reg_buf", because
6241 * vim_regexec_multi() can't be called recursively. */
6242 submatch_match = reg_match;
6243 submatch_mmatch = reg_mmatch;
6244 save_reg_maxline = reg_maxline;
6245 save_reg_win = reg_win;
6246 save_ireg_ic = ireg_ic;
6247 can_f_submatch = TRUE;
6248
6249 eval_result = eval_to_string(source + 2, NULL);
6250 if (eval_result != NULL)
6251 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006252 for (s = eval_result; *s != NUL; mb_ptr_adv(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 {
6254 /* Change NL to CR, so that it becomes a line break.
6255 * Skip over a backslashed character. */
6256 if (*s == NL)
6257 *s = CAR;
6258 else if (*s == '\\' && s[1] != NUL)
6259 ++s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 }
6261
6262 dst += STRLEN(eval_result);
6263 }
6264
6265 reg_match = submatch_match;
6266 reg_mmatch = submatch_mmatch;
6267 reg_maxline = save_reg_maxline;
6268 reg_win = save_reg_win;
6269 ireg_ic = save_ireg_ic;
6270 can_f_submatch = FALSE;
6271 }
6272#endif
6273 }
6274 else
6275 while ((c = *src++) != NUL)
6276 {
6277 if (c == '&' && magic)
6278 no = 0;
6279 else if (c == '\\' && *src != NUL)
6280 {
6281 if (*src == '&' && !magic)
6282 {
6283 ++src;
6284 no = 0;
6285 }
6286 else if ('0' <= *src && *src <= '9')
6287 {
6288 no = *src++ - '0';
6289 }
6290 else if (vim_strchr((char_u *)"uUlLeE", *src))
6291 {
6292 switch (*src++)
6293 {
6294 case 'u': func = (fptr)do_upper;
6295 continue;
6296 case 'U': func = (fptr)do_Upper;
6297 continue;
6298 case 'l': func = (fptr)do_lower;
6299 continue;
6300 case 'L': func = (fptr)do_Lower;
6301 continue;
6302 case 'e':
6303 case 'E': func = (fptr)NULL;
6304 continue;
6305 }
6306 }
6307 }
6308 if (no < 0) /* Ordinary character. */
6309 {
6310 if (c == '\\' && *src != NUL)
6311 {
6312 /* Check for abbreviations -- webb */
6313 switch (*src)
6314 {
6315 case 'r': c = CAR; ++src; break;
6316 case 'n': c = NL; ++src; break;
6317 case 't': c = TAB; ++src; break;
6318 /* Oh no! \e already has meaning in subst pat :-( */
6319 /* case 'e': c = ESC; ++src; break; */
6320 case 'b': c = Ctrl_H; ++src; break;
6321
6322 /* If "backslash" is TRUE the backslash will be removed
6323 * later. Used to insert a literal CR. */
6324 default: if (backslash)
6325 {
6326 if (copy)
6327 *dst = '\\';
6328 ++dst;
6329 }
6330 c = *src++;
6331 }
6332 }
6333
6334 /* Write to buffer, if copy is set. */
6335#ifdef FEAT_MBYTE
6336 if (has_mbyte && (l = (*mb_ptr2len_check)(src - 1)) > 1)
6337 {
6338 /* TODO: should use "func" here. */
6339 if (copy)
6340 mch_memmove(dst, src - 1, l);
6341 dst += l - 1;
6342 src += l - 1;
6343 }
6344 else
6345 {
6346#endif
6347 if (copy)
6348 {
6349 if (func == (fptr)NULL) /* just copy */
6350 *dst = c;
6351 else /* change case */
6352 func = (fptr)(func(dst, c));
6353 /* Turbo C complains without the typecast */
6354 }
6355#ifdef FEAT_MBYTE
6356 }
6357#endif
6358 dst++;
6359 }
6360 else
6361 {
6362 if (REG_MULTI)
6363 {
6364 clnum = reg_mmatch->startpos[no].lnum;
6365 if (clnum < 0 || reg_mmatch->endpos[no].lnum < 0)
6366 s = NULL;
6367 else
6368 {
6369 s = reg_getline(clnum) + reg_mmatch->startpos[no].col;
6370 if (reg_mmatch->endpos[no].lnum == clnum)
6371 len = reg_mmatch->endpos[no].col
6372 - reg_mmatch->startpos[no].col;
6373 else
6374 len = (int)STRLEN(s);
6375 }
6376 }
6377 else
6378 {
6379 s = reg_match->startp[no];
6380 if (reg_match->endp[no] == NULL)
6381 s = NULL;
6382 else
6383 len = (int)(reg_match->endp[no] - s);
6384 }
6385 if (s != NULL)
6386 {
6387 for (;;)
6388 {
6389 if (len == 0)
6390 {
6391 if (REG_MULTI)
6392 {
6393 if (reg_mmatch->endpos[no].lnum == clnum)
6394 break;
6395 if (copy)
6396 *dst = CAR;
6397 ++dst;
6398 s = reg_getline(++clnum);
6399 if (reg_mmatch->endpos[no].lnum == clnum)
6400 len = reg_mmatch->endpos[no].col;
6401 else
6402 len = (int)STRLEN(s);
6403 }
6404 else
6405 break;
6406 }
6407 else if (*s == NUL) /* we hit NUL. */
6408 {
6409 if (copy)
6410 EMSG(_(e_re_damg));
6411 goto exit;
6412 }
6413 else
6414 {
6415 if (backslash && (*s == CAR || *s == '\\'))
6416 {
6417 /*
6418 * Insert a backslash in front of a CR, otherwise
6419 * it will be replaced by a line break.
6420 * Number of backslashes will be halved later,
6421 * double them here.
6422 */
6423 if (copy)
6424 {
6425 dst[0] = '\\';
6426 dst[1] = *s;
6427 }
6428 dst += 2;
6429 }
6430#ifdef FEAT_MBYTE
6431 else if (has_mbyte && (l = (*mb_ptr2len_check)(s)) > 1)
6432 {
6433 /* TODO: should use "func" here. */
6434 if (copy)
6435 mch_memmove(dst, s, l);
6436 dst += l;
6437 s += l - 1;
6438 len -= l - 1;
6439 }
6440#endif
6441 else
6442 {
6443 if (copy)
6444 {
6445 if (func == (fptr)NULL) /* just copy */
6446 *dst = *s;
6447 else /* change case */
6448 func = (fptr)(func(dst, *s));
6449 /* Turbo C complains without the typecast */
6450 }
6451 ++dst;
6452 }
6453 ++s;
6454 --len;
6455 }
6456 }
6457 }
6458 no = -1;
6459 }
6460 }
6461 if (copy)
6462 *dst = NUL;
6463
6464exit:
6465 return (int)((dst - dest) + 1);
6466}
6467
6468#ifdef FEAT_EVAL
6469/*
6470 * Used for the submatch() function: get the string from tne n'th submatch in
6471 * allocated memory.
6472 * Returns NULL when not in a ":s" command and for a non-existing submatch.
6473 */
6474 char_u *
6475reg_submatch(no)
6476 int no;
6477{
6478 char_u *retval = NULL;
6479 char_u *s;
6480 int len;
6481 int round;
6482 linenr_T lnum;
6483
6484 if (!can_f_submatch)
6485 return NULL;
6486
6487 if (submatch_match == NULL)
6488 {
6489 /*
6490 * First round: compute the length and allocate memory.
6491 * Second round: copy the text.
6492 */
6493 for (round = 1; round <= 2; ++round)
6494 {
6495 lnum = submatch_mmatch->startpos[no].lnum;
6496 if (lnum < 0 || submatch_mmatch->endpos[no].lnum < 0)
6497 return NULL;
6498
6499 s = reg_getline(lnum) + submatch_mmatch->startpos[no].col;
6500 if (s == NULL) /* anti-crash check, cannot happen? */
6501 break;
6502 if (submatch_mmatch->endpos[no].lnum == lnum)
6503 {
6504 /* Within one line: take form start to end col. */
6505 len = submatch_mmatch->endpos[no].col
6506 - submatch_mmatch->startpos[no].col;
6507 if (round == 2)
6508 {
6509 STRNCPY(retval, s, len);
6510 retval[len] = NUL;
6511 }
6512 ++len;
6513 }
6514 else
6515 {
6516 /* Multiple lines: take start line from start col, middle
6517 * lines completely and end line up to end col. */
6518 len = (int)STRLEN(s);
6519 if (round == 2)
6520 {
6521 STRCPY(retval, s);
6522 retval[len] = '\n';
6523 }
6524 ++len;
6525 ++lnum;
6526 while (lnum < submatch_mmatch->endpos[no].lnum)
6527 {
6528 s = reg_getline(lnum++);
6529 if (round == 2)
6530 STRCPY(retval + len, s);
6531 len += (int)STRLEN(s);
6532 if (round == 2)
6533 retval[len] = '\n';
6534 ++len;
6535 }
6536 if (round == 2)
6537 STRNCPY(retval + len, reg_getline(lnum),
6538 submatch_mmatch->endpos[no].col);
6539 len += submatch_mmatch->endpos[no].col;
6540 if (round == 2)
6541 retval[len] = NUL;
6542 ++len;
6543 }
6544
6545 if (round == 1)
6546 {
6547 retval = lalloc((long_u)len, TRUE);
6548 if (s == NULL)
6549 return NULL;
6550 }
6551 }
6552 }
6553 else
6554 {
6555 if (submatch_match->endp[no] == NULL)
6556 retval = NULL;
6557 else
6558 {
6559 s = submatch_match->startp[no];
6560 retval = vim_strnsave(s, (int)(submatch_match->endp[no] - s));
6561 }
6562 }
6563
6564 return retval;
6565}
6566#endif