1 /* vi:set ts=8 sts=4 sw=4:
3 * Handling of regular expressions: vim_regcomp(), vim_regexec(), vim_regsub()
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.
15 * Copyright (c) 1986 by University of Toronto.
16 * Written by Henry Spencer. Not derived from licensed software.
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:
22 * 1. The author is not responsible for the consequences of use of
23 * this software, no matter how awful, even if they arise
26 * 2. The origin of this software must not be misrepresented, either
27 * by explicit claim or by omission.
29 * 3. Altered versions must be plainly marked as such, and must not
30 * be misrepresented as being the original software.
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.
36 * Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert
37 * Webb, Ciaran McCreesh and Bram Moolenaar.
38 * Named character class support added by Walter Briscoe (1998 Jul 01)
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:
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
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.
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
77 * 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.)
84 * pattern is coded like:
88 * <aa>\|<bb> BRANCH <aa> BRANCH <bb> --> END
90 * +------+ +----------+
93 * +------------------+
95 * <aa>* BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
97 * | +---------------+ |
98 * +---------------------------------------------+
101 * +----------------------+
103 * <aa>\+ BRANCH <aa> --> BRANCH --> BACK BRANCH --> NOTHING --> END
106 * +--------------------------------------------------+
109 * +-------------------------+
111 * <aa>\{} BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK END
113 * | +----------------+
114 * +-----------------------------------------------+
117 * <aa>\@!<bb> BRANCH NOMATCH <aa> --> END <bb> --> END
119 * | +----------------+ |
120 * +--------------------------------+
124 * \z[abc] BRANCH BRANCH a BRANCH b BRANCH c BRANCH NOTHING --> END
127 * | | +----------------+ |
128 * | +---------------------------+ |
129 * +------------------------------------------------------+
131 * They all start with a BRANCH for "\|" alternaties, even when there is only
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
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
150 #define PLUS 8 /* node Match this (simple) thing 1 or more
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 */
167 /* character classes: 20-48 normal, 50-78 include a line-break */
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
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)
203 #define MOPEN 80 /* -89 Mark this point in input as start of
204 * \( subexpr. MOPEN + 0 marks start of
206 #define MCLOSE 90 /* -99 Analogous to MOPEN. MCLOSE + 0 marks
208 #define BACKREF 100 /* -109 node Match same string again \1-\9 */
211 # define ZOPEN 110 /* -119 Mark this point in input as start of
213 # define ZCLOSE 120 /* -129 Analogous to ZOPEN. */
214 # define ZREF 130 /* -139 node Match external submatch \z1-\z9 */
217 #define BRACE_COMPLEX 140 /* -149 node Match nodes between m & n times */
219 #define NOPEN 150 /* Mark this point in input as start of
221 #define NCLOSE 151 /* Analogous to NOPEN. */
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. */
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 */
232 #define RE_MARK 207 /* mark cmp Match mark position */
233 #define RE_VISUAL 208 /* Match Visual area */
236 * Magic characters have a special meaning, they don't match literally.
237 * Magic characters are negative. This separates them from literal characters
238 * (possibly multi-byte). Only ASCII characters can be Magic.
240 #define Magic(x) ((int)(x) - 256)
241 #define un_Magic(x) ((x) + 256)
242 #define is_Magic(x) ((x) < 0)
244 static int no_Magic
__ARGS((int x
));
245 static int toggle_Magic
__ARGS((int x
));
266 * The first byte of the regexp internal "program" is actually this magic
267 * number; the start node begins in the second byte. It's used to catch the
268 * most severe mutilation of the program by the caller.
271 #define REGMAGIC 0234
276 * BRANCH The set of branches constituting a single choice are hooked
277 * together with their "next" pointers, since precedence prevents
278 * anything being concatenated to any individual branch. The
279 * "next" pointer of the last BRANCH in a choice points to the
280 * thing following the whole choice. This is also where the
281 * final "next" pointer of each individual branch points; each
282 * branch starts with the operand node of a BRANCH node.
284 * BACK Normal "next" pointers all implicitly point forward; BACK
285 * exists to make loop structures possible.
287 * STAR,PLUS '=', and complex '*' and '+', are implemented as circular
288 * BRANCH structures using BACK. Simple cases (one character
289 * per match) are implemented with STAR and PLUS for speed
290 * and to minimize recursive plunges.
292 * BRACE_LIMITS This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
293 * node, and defines the min and max limits to be used for that
296 * MOPEN,MCLOSE ...are numbered at compile time.
297 * ZOPEN,ZCLOSE ...ditto
301 * A node is one char of opcode followed by two chars of "next" pointer.
302 * "Next" pointers are stored as two 8-bit bytes, high order first. The
303 * value is a positive offset from the opcode of the node containing it.
304 * An operand, if any, simply follows the node. (Note that much of the
305 * code generation knows about this implicit relationship.)
307 * Using two bytes for the "next" pointer is vast overkill for most things,
308 * but allows patterns to get big without disasters.
310 #define OP(p) ((int)*(p))
311 #define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
312 #define OPERAND(p) ((p) + 3)
313 /* Obtain an operand that was stored as four bytes, MSB first. */
314 #define OPERAND_MIN(p) (((long)(p)[3] << 24) + ((long)(p)[4] << 16) \
315 + ((long)(p)[5] << 8) + (long)(p)[6])
316 /* Obtain a second operand stored as four bytes. */
317 #define OPERAND_MAX(p) OPERAND_MIN((p) + 4)
318 /* Obtain a second single-byte operand stored after a four bytes operand. */
319 #define OPERAND_CMP(p) (p)[7]
322 * Utility definitions.
324 #define UCHARAT(p) ((int)*(char_u *)(p))
326 /* Used for an error (down from) vim_regcomp(): give the error message, set
327 * rc_did_emsg and return NULL */
328 #define EMSG_RET_NULL(m) return (EMSG(m), rc_did_emsg = TRUE, (void *)NULL)
329 #define EMSG_M_RET_NULL(m, c) return (EMSG2((m), (c) ? "" : "\\"), rc_did_emsg = TRUE, (void *)NULL)
330 #define EMSG_RET_FAIL(m) return (EMSG(m), rc_did_emsg = TRUE, FAIL)
331 #define EMSG_ONE_RET_NULL EMSG_M_RET_NULL(_("E369: invalid item in %s%%[]"), reg_magic == MAGIC_ALL)
333 #define MAX_LIMIT (32767L << 16L)
335 static int re_multi_type
__ARGS((int));
336 static int cstrncmp
__ARGS((char_u
*s1
, char_u
*s2
, int *n
));
337 static char_u
*cstrchr
__ARGS((char_u
*, int));
340 static void regdump
__ARGS((char_u
*, regprog_T
*));
341 static char_u
*regprop
__ARGS((char_u
*));
348 * Return NOT_MULTI if c is not a "multi" operator.
349 * Return MULTI_ONE if c is a single "multi" operator.
350 * Return MULTI_MULT if c is a multi "multi" operator.
356 if (c
== Magic('@') || c
== Magic('=') || c
== Magic('?'))
358 if (c
== Magic('*') || c
== Magic('+') || c
== Magic('{'))
364 * Flags to be passed up and down.
366 #define HASWIDTH 0x1 /* Known never to match null string. */
367 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
368 #define SPSTART 0x4 /* Starts with * or +. */
369 #define HASNL 0x8 /* Contains some \n. */
370 #define HASLOOKBH 0x10 /* Contains "\@<=" or "\@<!". */
371 #define WORST 0 /* Worst case. */
374 * When regcode is set to this value, code is not emitted and size is computed
377 #define JUST_CALC_SIZE ((char_u *) -1)
379 static char_u
*reg_prev_sub
= NULL
;
381 #if defined(EXITFREE) || defined(PROTO)
385 vim_free(reg_prev_sub
);
390 * REGEXP_INRANGE contains all characters which are always special in a []
392 * REGEXP_ABBR contains all characters which act as abbreviations after '\'.
394 * \n - New line (NL).
395 * \r - Carriage Return (CR).
398 * \b - Backspace (Ctrl_H).
399 * \d - Character code in decimal, eg \d123
400 * \o - Character code in octal, eg \o80
401 * \x - Character code in hex, eg \x4a
402 * \u - Multibyte character code, eg \u20ac
403 * \U - Long multibyte character code, eg \U12345678
405 static char_u REGEXP_INRANGE
[] = "]^-n\\";
406 static char_u REGEXP_ABBR
[] = "nrtebdoxuU";
408 static int backslash_trans
__ARGS((int c
));
409 static int get_char_class
__ARGS((char_u
**pp
));
410 static int get_equi_class
__ARGS((char_u
**pp
));
411 static void reg_equi_class
__ARGS((int c
));
412 static int get_coll_element
__ARGS((char_u
**pp
));
413 static char_u
*skip_anyof
__ARGS((char_u
*p
));
414 static void init_class_tab
__ARGS((void));
417 * Translate '\x' to its control character, except "\n", which is Magic.
425 case 'r': return CAR
;
426 case 't': return TAB
;
427 case 'e': return ESC
;
434 * Check for a character class name "[:name:]". "pp" points to the '['.
435 * Returns one of the CLASS_ items. CLASS_NONE means that no item was
436 * recognized. Otherwise "pp" is advanced to after the item.
442 static const char *(class_names
[]) =
445 #define CLASS_ALNUM 0
447 #define CLASS_ALPHA 1
449 #define CLASS_BLANK 2
451 #define CLASS_CNTRL 3
453 #define CLASS_DIGIT 4
455 #define CLASS_GRAPH 5
457 #define CLASS_LOWER 6
459 #define CLASS_PRINT 7
461 #define CLASS_PUNCT 8
463 #define CLASS_SPACE 9
465 #define CLASS_UPPER 10
467 #define CLASS_XDIGIT 11
471 #define CLASS_RETURN 13
473 #define CLASS_BACKSPACE 14
475 #define CLASS_ESCAPE 15
477 #define CLASS_NONE 99
482 for (i
= 0; i
< sizeof(class_names
) / sizeof(*class_names
); ++i
)
483 if (STRNCMP(*pp
+ 2, class_names
[i
], STRLEN(class_names
[i
])) == 0)
485 *pp
+= STRLEN(class_names
[i
]) + 2;
493 * Specific version of character class functions.
494 * Using a table to keep this fast.
496 static short class_tab
[256];
498 #define RI_DIGIT 0x01
500 #define RI_OCTAL 0x04
503 #define RI_ALPHA 0x20
504 #define RI_LOWER 0x40
505 #define RI_UPPER 0x80
506 #define RI_WHITE 0x100
512 static int done
= FALSE
;
517 for (i
= 0; i
< 256; ++i
)
519 if (i
>= '0' && i
<= '7')
520 class_tab
[i
] = RI_DIGIT
+ RI_HEX
+ RI_OCTAL
+ RI_WORD
;
521 else if (i
>= '8' && i
<= '9')
522 class_tab
[i
] = RI_DIGIT
+ RI_HEX
+ RI_WORD
;
523 else if (i
>= 'a' && i
<= 'f')
524 class_tab
[i
] = RI_HEX
+ RI_WORD
+ RI_HEAD
+ RI_ALPHA
+ RI_LOWER
;
526 else if ((i
>= 'g' && i
<= 'i') || (i
>= 'j' && i
<= 'r')
527 || (i
>= 's' && i
<= 'z'))
529 else if (i
>= 'g' && i
<= 'z')
531 class_tab
[i
] = RI_WORD
+ RI_HEAD
+ RI_ALPHA
+ RI_LOWER
;
532 else if (i
>= 'A' && i
<= 'F')
533 class_tab
[i
] = RI_HEX
+ RI_WORD
+ RI_HEAD
+ RI_ALPHA
+ RI_UPPER
;
535 else if ((i
>= 'G' && i
<= 'I') || ( i
>= 'J' && i
<= 'R')
536 || (i
>= 'S' && i
<= 'Z'))
538 else if (i
>= 'G' && i
<= 'Z')
540 class_tab
[i
] = RI_WORD
+ RI_HEAD
+ RI_ALPHA
+ RI_UPPER
;
542 class_tab
[i
] = RI_WORD
+ RI_HEAD
;
546 class_tab
[' '] |= RI_WHITE
;
547 class_tab
['\t'] |= RI_WHITE
;
552 # define ri_digit(c) (c < 0x100 && (class_tab[c] & RI_DIGIT))
553 # define ri_hex(c) (c < 0x100 && (class_tab[c] & RI_HEX))
554 # define ri_octal(c) (c < 0x100 && (class_tab[c] & RI_OCTAL))
555 # define ri_word(c) (c < 0x100 && (class_tab[c] & RI_WORD))
556 # define ri_head(c) (c < 0x100 && (class_tab[c] & RI_HEAD))
557 # define ri_alpha(c) (c < 0x100 && (class_tab[c] & RI_ALPHA))
558 # define ri_lower(c) (c < 0x100 && (class_tab[c] & RI_LOWER))
559 # define ri_upper(c) (c < 0x100 && (class_tab[c] & RI_UPPER))
560 # define ri_white(c) (c < 0x100 && (class_tab[c] & RI_WHITE))
562 # define ri_digit(c) (class_tab[c] & RI_DIGIT)
563 # define ri_hex(c) (class_tab[c] & RI_HEX)
564 # define ri_octal(c) (class_tab[c] & RI_OCTAL)
565 # define ri_word(c) (class_tab[c] & RI_WORD)
566 # define ri_head(c) (class_tab[c] & RI_HEAD)
567 # define ri_alpha(c) (class_tab[c] & RI_ALPHA)
568 # define ri_lower(c) (class_tab[c] & RI_LOWER)
569 # define ri_upper(c) (class_tab[c] & RI_UPPER)
570 # define ri_white(c) (class_tab[c] & RI_WHITE)
573 /* flags for regflags */
574 #define RF_ICASE 1 /* ignore case */
575 #define RF_NOICASE 2 /* don't ignore case */
576 #define RF_HASNL 4 /* can match a NL */
577 #define RF_ICOMBINE 8 /* ignore combining characters */
578 #define RF_LOOKBH 16 /* uses "\@<=" or "\@<!" */
581 * Global work variables for vim_regcomp().
584 static char_u
*regparse
; /* Input-scan pointer. */
585 static int prevchr_len
; /* byte length of previous char */
586 static int num_complex_braces
; /* Complex \{...} count */
587 static int regnpar
; /* () count. */
589 static int regnzpar
; /* \z() count. */
590 static int re_has_z
; /* \z item detected */
592 static char_u
*regcode
; /* Code-emit pointer, or JUST_CALC_SIZE */
593 static long regsize
; /* Code size. */
594 static char_u had_endbrace
[NSUBEXP
]; /* flags, TRUE if end of () found */
595 static unsigned regflags
; /* RF_ flags for prog */
596 static long brace_min
[10]; /* Minimums for complex brace repeats */
597 static long brace_max
[10]; /* Maximums for complex brace repeats */
598 static int brace_count
[10]; /* Current counts for complex brace repeats */
599 #if defined(FEAT_SYN_HL) || defined(PROTO)
600 static int had_eol
; /* TRUE when EOL found by vim_regcomp() */
602 static int one_exactly
= FALSE
; /* only do one char for EXACTLY */
604 static int reg_magic
; /* magicness of the pattern: */
605 #define MAGIC_NONE 1 /* "\V" very unmagic */
606 #define MAGIC_OFF 2 /* "\M" or 'magic' off */
607 #define MAGIC_ON 3 /* "\m" or 'magic' */
608 #define MAGIC_ALL 4 /* "\v" very magic */
610 static int reg_string
; /* matching with a string instead of a buffer
612 static int reg_strict
; /* "[abc" is illegal */
615 * META contains all characters that may be magic, except '^' and '$'.
619 static char_u META
[] = "%&()*+.123456789<=>?@ACDFHIKLMOPSUVWX[_acdfhiklmnopsuvwxz{|~";
621 /* META[] is used often enough to justify turning it into a table. */
622 static char_u META_flags
[] = {
623 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
624 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
626 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
627 /* 1 2 3 4 5 6 7 8 9 < = > ? */
628 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
629 /* @ A C D F H I K L M O */
630 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
631 /* P S U V W X Z [ _ */
632 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1,
633 /* a c d f h i k l m n o */
634 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
635 /* p s u v w x z { | ~ */
636 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
642 /* arguments for reg() */
643 #define REG_NOPAREN 0 /* toplevel reg() */
644 #define REG_PAREN 1 /* \(\) */
645 #define REG_ZPAREN 2 /* \z(\) */
646 #define REG_NPAREN 3 /* \%(\) */
649 * Forward declarations for vim_regcomp()'s friends.
651 static void initchr
__ARGS((char_u
*));
652 static int getchr
__ARGS((void));
653 static void skipchr_keepstart
__ARGS((void));
654 static int peekchr
__ARGS((void));
655 static void skipchr
__ARGS((void));
656 static void ungetchr
__ARGS((void));
657 static int gethexchrs
__ARGS((int maxinputlen
));
658 static int getoctchrs
__ARGS((void));
659 static int getdecchrs
__ARGS((void));
660 static int coll_get_char
__ARGS((void));
661 static void regcomp_start
__ARGS((char_u
*expr
, int flags
));
662 static char_u
*reg
__ARGS((int, int *));
663 static char_u
*regbranch
__ARGS((int *flagp
));
664 static char_u
*regconcat
__ARGS((int *flagp
));
665 static char_u
*regpiece
__ARGS((int *));
666 static char_u
*regatom
__ARGS((int *));
667 static char_u
*regnode
__ARGS((int));
669 static int use_multibytecode
__ARGS((int c
));
671 static int prog_magic_wrong
__ARGS((void));
672 static char_u
*regnext
__ARGS((char_u
*));
673 static void regc
__ARGS((int b
));
675 static void regmbc
__ARGS((int c
));
677 # define regmbc(c) regc(c)
679 static void reginsert
__ARGS((int, char_u
*));
680 static void reginsert_limits
__ARGS((int, long, long, char_u
*));
681 static char_u
*re_put_long
__ARGS((char_u
*pr
, long_u val
));
682 static int read_limits
__ARGS((long *, long *));
683 static void regtail
__ARGS((char_u
*, char_u
*));
684 static void regoptail
__ARGS((char_u
*, char_u
*));
687 * Return TRUE if compiled regular expression "prog" can match a line break.
693 return (prog
->regflags
& RF_HASNL
);
697 * Return TRUE if compiled regular expression "prog" looks before the start
698 * position (pattern contains "\@<=" or "\@<!").
704 return (prog
->regflags
& RF_LOOKBH
);
708 * Check for an equivalence class name "[=a=]". "pp" points to the '['.
709 * Returns a character representing the class. Zero means that no item was
710 * recognized. Otherwise "pp" is advanced to after the item.
724 l
= (*mb_ptr2len
)(p
+ 2);
726 if (p
[l
+ 2] == '=' && p
[l
+ 3] == ']')
730 c
= mb_ptr2char(p
+ 2);
742 * Produce the bytes for equivalence class "c".
743 * Currently only handles latin1, latin9 and utf-8.
750 if (enc_utf8
|| STRCMP(p_enc
, "latin1") == 0
751 || STRCMP(p_enc
, "iso-8859-15") == 0)
756 case 'A': case '\300': case '\301': case '\302':
757 case '\303': case '\304': case '\305':
758 regmbc('A'); regmbc('\300'); regmbc('\301');
759 regmbc('\302'); regmbc('\303'); regmbc('\304');
762 case 'C': case '\307':
763 regmbc('C'); regmbc('\307');
765 case 'E': case '\310': case '\311': case '\312': case '\313':
766 regmbc('E'); regmbc('\310'); regmbc('\311');
767 regmbc('\312'); regmbc('\313');
769 case 'I': case '\314': case '\315': case '\316': case '\317':
770 regmbc('I'); regmbc('\314'); regmbc('\315');
771 regmbc('\316'); regmbc('\317');
773 case 'N': case '\321':
774 regmbc('N'); regmbc('\321');
776 case 'O': case '\322': case '\323': case '\324': case '\325':
778 regmbc('O'); regmbc('\322'); regmbc('\323');
779 regmbc('\324'); regmbc('\325'); regmbc('\326');
781 case 'U': case '\331': case '\332': case '\333': case '\334':
782 regmbc('U'); regmbc('\331'); regmbc('\332');
783 regmbc('\333'); regmbc('\334');
785 case 'Y': case '\335':
786 regmbc('Y'); regmbc('\335');
788 case 'a': case '\340': case '\341': case '\342':
789 case '\343': case '\344': case '\345':
790 regmbc('a'); regmbc('\340'); regmbc('\341');
791 regmbc('\342'); regmbc('\343'); regmbc('\344');
794 case 'c': case '\347':
795 regmbc('c'); regmbc('\347');
797 case 'e': case '\350': case '\351': case '\352': case '\353':
798 regmbc('e'); regmbc('\350'); regmbc('\351');
799 regmbc('\352'); regmbc('\353');
801 case 'i': case '\354': case '\355': case '\356': case '\357':
802 regmbc('i'); regmbc('\354'); regmbc('\355');
803 regmbc('\356'); regmbc('\357');
805 case 'n': case '\361':
806 regmbc('n'); regmbc('\361');
808 case 'o': case '\362': case '\363': case '\364': case '\365':
810 regmbc('o'); regmbc('\362'); regmbc('\363');
811 regmbc('\364'); regmbc('\365'); regmbc('\366');
813 case 'u': case '\371': case '\372': case '\373': case '\374':
814 regmbc('u'); regmbc('\371'); regmbc('\372');
815 regmbc('\373'); regmbc('\374');
817 case 'y': case '\375': case '\377':
818 regmbc('y'); regmbc('\375'); regmbc('\377');
826 * Check for a collating element "[.a.]". "pp" points to the '['.
827 * Returns a character. Zero means that no item was recognized. Otherwise
828 * "pp" is advanced to after the item.
829 * Currently only single characters are recognized!
843 l
= (*mb_ptr2len
)(p
+ 2);
845 if (p
[l
+ 2] == '.' && p
[l
+ 3] == ']')
849 c
= mb_ptr2char(p
+ 2);
862 * Skip over a "[]" range.
863 * "p" must point to the character after the '['.
864 * The returned pointer is on the matching ']', or the terminating NUL.
870 int cpo_lit
; /* 'cpoptions' contains 'l' flag */
871 int cpo_bsl
; /* 'cpoptions' contains '\' flag */
876 cpo_lit
= vim_strchr(p_cpo
, CPO_LITERAL
) != NULL
;
877 cpo_bsl
= vim_strchr(p_cpo
, CPO_BACKSL
) != NULL
;
879 if (*p
== '^') /* Complement of range. */
881 if (*p
== ']' || *p
== '-')
883 while (*p
!= NUL
&& *p
!= ']')
886 if (has_mbyte
&& (l
= (*mb_ptr2len
)(p
)) > 1)
893 if (*p
!= ']' && *p
!= NUL
)
898 && (vim_strchr(REGEXP_INRANGE
, p
[1]) != NULL
899 || (!cpo_lit
&& vim_strchr(REGEXP_ABBR
, p
[1]) != NULL
)))
903 if (get_char_class(&p
) == CLASS_NONE
904 && get_equi_class(&p
) == 0
905 && get_coll_element(&p
) == 0)
906 ++p
; /* It was not a class name */
916 * Skip past regular expression.
917 * Stop at end of "startp" or where "dirc" is found ('/', '?', etc).
918 * Take care of characters with a backslash in front of it.
919 * Skip strings inside [ and ].
920 * When "newp" is not NULL and "dirc" is '?', make an allocated copy of the
921 * expression and change "\?" to "?". If "*newp" is not NULL the expression
922 * is changed in-place.
925 skip_regexp(startp
, dirc
, magic
, newp
)
939 for (; p
[0] != NUL
; mb_ptr_adv(p
))
941 if (p
[0] == dirc
) /* found end of regexp */
943 if ((p
[0] == '[' && mymagic
>= MAGIC_ON
)
944 || (p
[0] == '\\' && p
[1] == '[' && mymagic
<= MAGIC_OFF
))
946 p
= skip_anyof(p
+ 1);
950 else if (p
[0] == '\\' && p
[1] != NUL
)
952 if (dirc
== '?' && newp
!= NULL
&& p
[1] == '?')
954 /* change "\?" to "?", make a copy first. */
957 *newp
= vim_strsave(startp
);
959 p
= *newp
+ (p
- startp
);
962 mch_memmove(p
, p
+ 1, STRLEN(p
));
967 ++p
; /* skip next character */
971 mymagic
= MAGIC_NONE
;
978 * vim_regcomp() - compile a regular expression into internal code
979 * Returns the program in allocated space. Returns NULL for an error.
981 * We can't allocate space until we know how big the compiled form will be,
982 * but we can't compile it (and thus know how big it is) until we've got a
983 * place to put the code. So we cheat: we compile it twice, once with code
984 * generation turned off and size counting turned on, and once "for real".
985 * This also means that we don't allocate space until we are sure that the
986 * thing really will compile successfully, and we never have to move the
987 * code and thus invalidate pointers into it. (Note that it has to be in
988 * one piece because vim_free() must be able to free it all.)
990 * Whether upper/lower case is to be ignored is decided when executing the
991 * program, it does not matter here.
993 * Beware that the optimization-preparation code in here knows about some
994 * of the structure of the compiled regexp.
995 * "re_flags": RE_MAGIC and/or RE_STRING.
998 vim_regcomp(expr
, re_flags
)
1009 EMSG_RET_NULL(_(e_null
));
1014 * First pass: determine size, legality.
1016 regcomp_start(expr
, re_flags
);
1017 regcode
= JUST_CALC_SIZE
;
1019 if (reg(REG_NOPAREN
, &flags
) == NULL
)
1022 /* Small enough for pointer-storage convention? */
1023 #ifdef SMALL_MALLOC /* 16 bit storage allocation */
1024 if (regsize
>= 65536L - 256L)
1025 EMSG_RET_NULL(_("E339: Pattern too long"));
1028 /* Allocate space. */
1029 r
= (regprog_T
*)lalloc(sizeof(regprog_T
) + regsize
, TRUE
);
1034 * Second pass: emit code.
1036 regcomp_start(expr
, re_flags
);
1037 regcode
= r
->program
;
1039 if (reg(REG_NOPAREN
, &flags
) == NULL
)
1045 /* Dig out information for optimizations. */
1046 r
->regstart
= NUL
; /* Worst-case defaults. */
1050 r
->regflags
= regflags
;
1052 r
->regflags
|= RF_HASNL
;
1053 if (flags
& HASLOOKBH
)
1054 r
->regflags
|= RF_LOOKBH
;
1056 /* Remember whether this pattern has any \z specials in it. */
1057 r
->reghasz
= re_has_z
;
1059 scan
= r
->program
+ 1; /* First BRANCH. */
1060 if (OP(regnext(scan
)) == END
) /* Only one top-level choice. */
1062 scan
= OPERAND(scan
);
1064 /* Starting-point info. */
1065 if (OP(scan
) == BOL
|| OP(scan
) == RE_BOF
)
1068 scan
= regnext(scan
);
1071 if (OP(scan
) == EXACTLY
)
1075 r
->regstart
= (*mb_ptr2char
)(OPERAND(scan
));
1078 r
->regstart
= *OPERAND(scan
);
1080 else if ((OP(scan
) == BOW
1082 || OP(scan
) == NOTHING
1083 || OP(scan
) == MOPEN
+ 0 || OP(scan
) == NOPEN
1084 || OP(scan
) == MCLOSE
+ 0 || OP(scan
) == NCLOSE
)
1085 && OP(regnext(scan
)) == EXACTLY
)
1089 r
->regstart
= (*mb_ptr2char
)(OPERAND(regnext(scan
)));
1092 r
->regstart
= *OPERAND(regnext(scan
));
1096 * If there's something expensive in the r.e., find the longest
1097 * literal string that must appear and make it the regmust. Resolve
1098 * ties in favor of later strings, since the regstart check works
1099 * with the beginning of the r.e. and avoiding duplication
1100 * strengthens checking. Not a strong reason, but sufficient in the
1101 * absence of others.
1104 * When the r.e. starts with BOW, it is faster to look for a regmust
1105 * first. Used a lot for "#" and "*" commands. (Added by mool).
1107 if ((flags
& SPSTART
|| OP(scan
) == BOW
|| OP(scan
) == EOW
)
1108 && !(flags
& HASNL
))
1112 for (; scan
!= NULL
; scan
= regnext(scan
))
1113 if (OP(scan
) == EXACTLY
&& STRLEN(OPERAND(scan
)) >= (size_t)len
)
1115 longest
= OPERAND(scan
);
1116 len
= (int)STRLEN(OPERAND(scan
));
1118 r
->regmust
= longest
;
1129 * Setup to parse the regexp. Used once to get the length and once to do it.
1132 regcomp_start(expr
, re_flags
)
1134 int re_flags
; /* see vim_regcomp() */
1137 if (re_flags
& RE_MAGIC
)
1138 reg_magic
= MAGIC_ON
;
1140 reg_magic
= MAGIC_OFF
;
1141 reg_string
= (re_flags
& RE_STRING
);
1142 reg_strict
= (re_flags
& RE_STRICT
);
1144 num_complex_braces
= 0;
1146 vim_memset(had_endbrace
, 0, sizeof(had_endbrace
));
1153 #if defined(FEAT_SYN_HL) || defined(PROTO)
1158 #if defined(FEAT_SYN_HL) || defined(PROTO)
1160 * Check if during the previous call to vim_regcomp the EOL item "$" has been
1161 * found. This is messy, but it works fine.
1164 vim_regcomp_had_eol()
1171 * reg - regular expression, i.e. main body or parenthesized thing
1173 * Caller must absorb opening parenthesis.
1175 * Combining parenthesis handling with the base level of regular expression
1176 * is a trifle forced, but the need to tie the tails of the branches to what
1177 * follows makes it hard to avoid.
1181 int paren
; /* REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN */
1190 *flagp
= HASWIDTH
; /* Tentatively. */
1193 if (paren
== REG_ZPAREN
)
1195 /* Make a ZOPEN node. */
1196 if (regnzpar
>= NSUBEXP
)
1197 EMSG_RET_NULL(_("E50: Too many \\z("));
1200 ret
= regnode(ZOPEN
+ parno
);
1204 if (paren
== REG_PAREN
)
1206 /* Make a MOPEN node. */
1207 if (regnpar
>= NSUBEXP
)
1208 EMSG_M_RET_NULL(_("E51: Too many %s("), reg_magic
== MAGIC_ALL
);
1211 ret
= regnode(MOPEN
+ parno
);
1213 else if (paren
== REG_NPAREN
)
1215 /* Make a NOPEN node. */
1216 ret
= regnode(NOPEN
);
1221 /* Pick up the branches, linking them together. */
1222 br
= regbranch(&flags
);
1226 regtail(ret
, br
); /* [MZ]OPEN -> first. */
1229 /* If one of the branches can be zero-width, the whole thing can.
1230 * If one of the branches has * at start or matches a line-break, the
1231 * whole thing can. */
1232 if (!(flags
& HASWIDTH
))
1233 *flagp
&= ~HASWIDTH
;
1234 *flagp
|= flags
& (SPSTART
| HASNL
| HASLOOKBH
);
1235 while (peekchr() == Magic('|'))
1238 br
= regbranch(&flags
);
1241 regtail(ret
, br
); /* BRANCH -> BRANCH. */
1242 if (!(flags
& HASWIDTH
))
1243 *flagp
&= ~HASWIDTH
;
1244 *flagp
|= flags
& (SPSTART
| HASNL
| HASLOOKBH
);
1247 /* Make a closing node, and hook it on the end. */
1250 paren
== REG_ZPAREN
? ZCLOSE
+ parno
:
1252 paren
== REG_PAREN
? MCLOSE
+ parno
:
1253 paren
== REG_NPAREN
? NCLOSE
: END
);
1254 regtail(ret
, ender
);
1256 /* Hook the tails of the branches to the closing node. */
1257 for (br
= ret
; br
!= NULL
; br
= regnext(br
))
1258 regoptail(br
, ender
);
1260 /* Check for proper termination. */
1261 if (paren
!= REG_NOPAREN
&& getchr() != Magic(')'))
1264 if (paren
== REG_ZPAREN
)
1265 EMSG_RET_NULL(_("E52: Unmatched \\z("));
1268 if (paren
== REG_NPAREN
)
1269 EMSG_M_RET_NULL(_("E53: Unmatched %s%%("), reg_magic
== MAGIC_ALL
);
1271 EMSG_M_RET_NULL(_("E54: Unmatched %s("), reg_magic
== MAGIC_ALL
);
1273 else if (paren
== REG_NOPAREN
&& peekchr() != NUL
)
1275 if (curchr
== Magic(')'))
1276 EMSG_M_RET_NULL(_("E55: Unmatched %s)"), reg_magic
== MAGIC_ALL
);
1278 EMSG_RET_NULL(_(e_trailing
)); /* "Can't happen". */
1282 * Here we set the flag allowing back references to this set of
1285 if (paren
== REG_PAREN
)
1286 had_endbrace
[parno
] = TRUE
; /* have seen the close paren */
1291 * regbranch - one alternative of an | operator
1293 * Implements the & operator.
1300 char_u
*chain
= NULL
;
1304 *flagp
= WORST
| HASNL
; /* Tentatively. */
1306 ret
= regnode(BRANCH
);
1309 latest
= regconcat(&flags
);
1312 /* If one of the branches has width, the whole thing has. If one of
1313 * the branches anchors at start-of-line, the whole thing does.
1314 * If one of the branches uses look-behind, the whole thing does. */
1315 *flagp
|= flags
& (HASWIDTH
| SPSTART
| HASLOOKBH
);
1316 /* If one of the branches doesn't match a line-break, the whole thing
1318 *flagp
&= ~HASNL
| (flags
& HASNL
);
1320 regtail(chain
, latest
);
1321 if (peekchr() != Magic('&'))
1324 regtail(latest
, regnode(END
)); /* operand ends */
1325 reginsert(MATCH
, latest
);
1333 * regbranch - one alternative of an | or & operator
1335 * Implements the concatenation operator.
1341 char_u
*first
= NULL
;
1342 char_u
*chain
= NULL
;
1347 *flagp
= WORST
; /* Tentatively. */
1361 regflags
|= RF_ICOMBINE
;
1363 skipchr_keepstart();
1366 regflags
|= RF_ICASE
;
1367 skipchr_keepstart();
1370 regflags
|= RF_NOICASE
;
1371 skipchr_keepstart();
1374 reg_magic
= MAGIC_ALL
;
1375 skipchr_keepstart();
1379 reg_magic
= MAGIC_ON
;
1380 skipchr_keepstart();
1384 reg_magic
= MAGIC_OFF
;
1385 skipchr_keepstart();
1389 reg_magic
= MAGIC_NONE
;
1390 skipchr_keepstart();
1394 latest
= regpiece(&flags
);
1397 *flagp
|= flags
& (HASWIDTH
| HASNL
| HASLOOKBH
);
1398 if (chain
== NULL
) /* First piece. */
1399 *flagp
|= flags
& SPSTART
;
1401 regtail(chain
, latest
);
1408 if (first
== NULL
) /* Loop ran zero times. */
1409 first
= regnode(NOTHING
);
1414 * regpiece - something followed by possible [*+=]
1416 * Note that the branching code sequences used for = and the general cases
1417 * of * and + are somewhat optimized: they use the same NOTHING node as
1418 * both the endmarker for their branch list and the body of the last branch.
1419 * It might seem that this node could be dispensed with entirely, but the
1420 * endmarker role is not redundant.
1433 ret
= regatom(&flags
);
1438 if (re_multi_type(op
) == NOT_MULTI
)
1444 *flagp
= (WORST
| SPSTART
| (flags
& (HASNL
| HASLOOKBH
)));
1451 reginsert(STAR
, ret
);
1454 /* Emit x* as (x&|), where & means "self". */
1455 reginsert(BRANCH
, ret
); /* Either x */
1456 regoptail(ret
, regnode(BACK
)); /* and loop */
1457 regoptail(ret
, ret
); /* back */
1458 regtail(ret
, regnode(BRANCH
)); /* or */
1459 regtail(ret
, regnode(NOTHING
)); /* null. */
1465 reginsert(PLUS
, ret
);
1468 /* Emit x+ as x(&|), where & means "self". */
1469 next
= regnode(BRANCH
); /* Either */
1471 regtail(regnode(BACK
), ret
); /* loop back */
1472 regtail(next
, regnode(BRANCH
)); /* or */
1473 regtail(ret
, regnode(NOTHING
)); /* null. */
1475 *flagp
= (WORST
| HASWIDTH
| (flags
& (HASNL
| HASLOOKBH
)));
1482 switch (no_Magic(getchr()))
1484 case '=': lop
= MATCH
; break; /* \@= */
1485 case '!': lop
= NOMATCH
; break; /* \@! */
1486 case '>': lop
= SUBPAT
; break; /* \@> */
1487 case '<': switch (no_Magic(getchr()))
1489 case '=': lop
= BEHIND
; break; /* \@<= */
1490 case '!': lop
= NOBEHIND
; break; /* \@<! */
1494 EMSG_M_RET_NULL(_("E59: invalid character after %s@"),
1495 reg_magic
== MAGIC_ALL
);
1496 /* Look behind must match with behind_pos. */
1497 if (lop
== BEHIND
|| lop
== NOBEHIND
)
1499 regtail(ret
, regnode(BHPOS
));
1500 *flagp
|= HASLOOKBH
;
1502 regtail(ret
, regnode(END
)); /* operand ends */
1503 reginsert(lop
, ret
);
1509 /* Emit x= as (x|) */
1510 reginsert(BRANCH
, ret
); /* Either x */
1511 regtail(ret
, regnode(BRANCH
)); /* or */
1512 next
= regnode(NOTHING
); /* null. */
1514 regoptail(ret
, next
);
1518 if (!read_limits(&minval
, &maxval
))
1522 reginsert(BRACE_SIMPLE
, ret
);
1523 reginsert_limits(BRACE_LIMITS
, minval
, maxval
, ret
);
1527 if (num_complex_braces
>= 10)
1528 EMSG_M_RET_NULL(_("E60: Too many complex %s{...}s"),
1529 reg_magic
== MAGIC_ALL
);
1530 reginsert(BRACE_COMPLEX
+ num_complex_braces
, ret
);
1531 regoptail(ret
, regnode(BACK
));
1532 regoptail(ret
, ret
);
1533 reginsert_limits(BRACE_LIMITS
, minval
, maxval
, ret
);
1534 ++num_complex_braces
;
1536 if (minval
> 0 && maxval
> 0)
1537 *flagp
= (HASWIDTH
| (flags
& (HASNL
| HASLOOKBH
)));
1540 if (re_multi_type(peekchr()) != NOT_MULTI
)
1542 /* Can't have a multi follow a multi. */
1543 if (peekchr() == Magic('*'))
1544 sprintf((char *)IObuff
, _("E61: Nested %s*"),
1545 reg_magic
>= MAGIC_ON
? "" : "\\");
1547 sprintf((char *)IObuff
, _("E62: Nested %s%c"),
1548 reg_magic
== MAGIC_ALL
? "" : "\\", no_Magic(peekchr()));
1549 EMSG_RET_NULL(IObuff
);
1556 * regatom - the lowest level
1558 * Optimization: gobbles an entire sequence of ordinary characters so that
1559 * it can turn them into a single node, which is smaller to store and
1560 * faster to run. Don't do this when one_exactly is set.
1568 int cpo_lit
; /* 'cpoptions' contains 'l' flag */
1569 int cpo_bsl
; /* 'cpoptions' contains '\' flag */
1571 static char_u
*classchars
= (char_u
*)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
1572 static int classcodes
[] = {ANY
, IDENT
, SIDENT
, KWORD
, SKWORD
,
1573 FNAME
, SFNAME
, PRINT
, SPRINT
,
1574 WHITE
, NWHITE
, DIGIT
, NDIGIT
,
1575 HEX
, NHEX
, OCTAL
, NOCTAL
,
1576 WORD
, NWORD
, HEAD
, NHEAD
,
1577 ALPHA
, NALPHA
, LOWER
, NLOWER
,
1583 *flagp
= WORST
; /* Tentatively. */
1584 cpo_lit
= vim_strchr(p_cpo
, CPO_LITERAL
) != NULL
;
1585 cpo_bsl
= vim_strchr(p_cpo
, CPO_BACKSL
) != NULL
;
1596 #if defined(FEAT_SYN_HL) || defined(PROTO)
1610 c
= no_Magic(getchr());
1611 if (c
== '^') /* "\_^" is start-of-line */
1616 if (c
== '$') /* "\_$" is end-of-line */
1619 #if defined(FEAT_SYN_HL) || defined(PROTO)
1628 /* "\_[" is character range plus newline */
1632 /* "\_x" is character class plus newline */
1636 * Character classes.
1665 p
= vim_strchr(classchars
, no_Magic(c
));
1667 EMSG_RET_NULL(_("E63: invalid use of \\_"));
1669 /* When '.' is followed by a composing char ignore the dot, so that
1670 * the composing char is matched here. */
1671 if (enc_utf8
&& c
== Magic('.') && utf_iscomposing(peekchr()))
1677 ret
= regnode(classcodes
[p
- classchars
] + extra
);
1678 *flagp
|= HASWIDTH
| SIMPLE
;
1684 /* In a string "\n" matches a newline character. */
1685 ret
= regnode(EXACTLY
);
1688 *flagp
|= HASWIDTH
| SIMPLE
;
1692 /* In buffer text "\n" matches the end of a line. */
1693 ret
= regnode(NEWL
);
1694 *flagp
|= HASWIDTH
| HASNL
;
1701 ret
= reg(REG_PAREN
, &flags
);
1704 *flagp
|= flags
& (HASWIDTH
| SPSTART
| HASNL
| HASLOOKBH
);
1711 EMSG_RET_NULL(_(e_internal
)); /* Supposed to be caught earlier. */
1721 sprintf((char *)IObuff
, _("E64: %s%c follows nothing"),
1722 (c
== '*' ? reg_magic
>= MAGIC_ON
: reg_magic
== MAGIC_ALL
)
1724 EMSG_RET_NULL(IObuff
);
1727 case Magic('~'): /* previous substitute pattern */
1728 if (reg_prev_sub
!= NULL
)
1732 ret
= regnode(EXACTLY
);
1737 if (*reg_prev_sub
!= NUL
)
1740 if ((lp
- reg_prev_sub
) == 1)
1745 EMSG_RET_NULL(_(e_nopresub
));
1760 refnum
= c
- Magic('0');
1762 * Check if the back reference is legal. We must have seen the
1764 * TODO: Should also check that we don't refer to something
1765 * that is repeated (+*=): what instance of the repetition
1768 if (!had_endbrace
[refnum
])
1770 /* Trick: check if "@<=" or "@<!" follows, in which case
1771 * the \1 can appear before the referenced match. */
1772 for (p
= regparse
; *p
!= NUL
; ++p
)
1773 if (p
[0] == '@' && p
[1] == '<'
1774 && (p
[2] == '!' || p
[2] == '='))
1777 EMSG_RET_NULL(_("E65: Illegal back reference"));
1779 ret
= regnode(BACKREF
+ refnum
);
1785 c
= no_Magic(getchr());
1789 case '(': if (reg_do_extmatch
!= REX_SET
)
1790 EMSG_RET_NULL(_("E66: \\z( not allowed here"));
1793 ret
= reg(REG_ZPAREN
, &flags
);
1796 *flagp
|= flags
& (HASWIDTH
|SPSTART
|HASNL
|HASLOOKBH
);
1808 case '9': if (reg_do_extmatch
!= REX_USE
)
1809 EMSG_RET_NULL(_("E67: \\z1 et al. not allowed here"));
1810 ret
= regnode(ZREF
+ c
- '0');
1815 case 's': ret
= regnode(MOPEN
+ 0);
1818 case 'e': ret
= regnode(MCLOSE
+ 0);
1821 default: EMSG_RET_NULL(_("E68: Invalid character after \\z"));
1828 c
= no_Magic(getchr());
1831 /* () without a back reference */
1835 ret
= reg(REG_NPAREN
, &flags
);
1838 *flagp
|= flags
& (HASWIDTH
| SPSTART
| HASNL
| HASLOOKBH
);
1841 /* Catch \%^ and \%$ regardless of where they appear in the
1842 * pattern -- regardless of whether or not it makes sense. */
1844 ret
= regnode(RE_BOF
);
1848 ret
= regnode(RE_EOF
);
1852 ret
= regnode(CURSOR
);
1856 ret
= regnode(RE_VISUAL
);
1859 /* \%[abc]: Emit as a list of branches, all ending at the last
1860 * branch which matches nothing. */
1862 if (one_exactly
) /* doesn't nest */
1866 char_u
*lastnode
= NULL
;
1870 while ((c
= getchr()) != ']')
1873 EMSG_M_RET_NULL(_("E69: Missing ] after %s%%["),
1874 reg_magic
== MAGIC_ALL
);
1875 br
= regnode(BRANCH
);
1879 regtail(lastnode
, br
);
1883 lastnode
= regatom(flagp
);
1884 one_exactly
= FALSE
;
1885 if (lastnode
== NULL
)
1889 EMSG_M_RET_NULL(_("E70: Empty %s%%[]"),
1890 reg_magic
== MAGIC_ALL
);
1891 lastbranch
= regnode(BRANCH
);
1892 br
= regnode(NOTHING
);
1893 if (ret
!= JUST_CALC_SIZE
)
1895 regtail(lastnode
, br
);
1896 regtail(lastbranch
, br
);
1897 /* connect all branches to the NOTHING
1898 * branch at the end */
1899 for (br
= ret
; br
!= lastnode
; )
1901 if (OP(br
) == BRANCH
)
1903 regtail(br
, lastbranch
);
1910 *flagp
&= ~HASWIDTH
;
1914 case 'd': /* %d123 decimal */
1915 case 'o': /* %o123 octal */
1916 case 'x': /* %xab hex 2 */
1917 case 'u': /* %uabcd hex 4 */
1918 case 'U': /* %U1234abcd hex 8 */
1924 case 'd': i
= getdecchrs(); break;
1925 case 'o': i
= getoctchrs(); break;
1926 case 'x': i
= gethexchrs(2); break;
1927 case 'u': i
= gethexchrs(4); break;
1928 case 'U': i
= gethexchrs(8); break;
1929 default: i
= -1; break;
1934 _("E678: Invalid character after %s%%[dxouU]"),
1935 reg_magic
== MAGIC_ALL
);
1937 if (use_multibytecode(i
))
1938 ret
= regnode(MULTIBYTECODE
);
1941 ret
= regnode(EXACTLY
);
1956 if (VIM_ISDIGIT(c
) || c
== '<' || c
== '>'
1963 if (cmp
== '<' || cmp
== '>')
1965 while (VIM_ISDIGIT(c
))
1967 n
= n
* 10 + (c
- '0');
1970 if (c
== '\'' && n
== 0)
1972 /* "\%'m", "\%<'m" and "\%>'m": Mark */
1974 ret
= regnode(RE_MARK
);
1975 if (ret
== JUST_CALC_SIZE
)
1984 else if (c
== 'l' || c
== 'c' || c
== 'v')
1987 ret
= regnode(RE_LNUM
);
1989 ret
= regnode(RE_COL
);
1991 ret
= regnode(RE_VCOL
);
1992 if (ret
== JUST_CALC_SIZE
)
1996 /* put the number and the optional
1997 * comparator after the opcode */
1998 regcode
= re_put_long(regcode
, n
);
2005 EMSG_M_RET_NULL(_("E71: Invalid character after %s%%"),
2006 reg_magic
== MAGIC_ALL
);
2017 * If there is no matching ']', we assume the '[' is a normal
2018 * character. This makes 'incsearch' and ":help [" work.
2020 lp
= skip_anyof(regparse
);
2021 if (*lp
== ']') /* there is a matching ']' */
2023 int startc
= -1; /* > 0 when next '-' is a range */
2027 * In a character class, different parsing rules apply.
2028 * Not even \ is special anymore, nothing is.
2030 if (*regparse
== '^') /* Complement of range. */
2032 ret
= regnode(ANYBUT
+ extra
);
2036 ret
= regnode(ANYOF
+ extra
);
2038 /* At the start ']' and '-' mean the literal character. */
2039 if (*regparse
== ']' || *regparse
== '-')
2045 while (*regparse
!= NUL
&& *regparse
!= ']')
2047 if (*regparse
== '-')
2050 /* The '-' is not used for a range at the end and
2051 * after or before a '\n'. */
2052 if (*regparse
== ']' || *regparse
== NUL
2054 || (regparse
[0] == '\\' && regparse
[1] == 'n'))
2057 startc
= '-'; /* [--x] is a range */
2061 /* Also accept "a-[.z.]" */
2063 if (*regparse
== '[')
2064 endc
= get_coll_element(®parse
);
2069 endc
= mb_ptr2char_adv(®parse
);
2075 /* Handle \o40, \x20 and \u20AC style sequences */
2076 if (endc
== '\\' && !cpo_lit
&& !cpo_bsl
)
2077 endc
= coll_get_char();
2080 EMSG_RET_NULL(_(e_invrange
));
2082 if (has_mbyte
&& ((*mb_char2len
)(startc
) > 1
2083 || (*mb_char2len
)(endc
) > 1))
2085 /* Limit to a range of 256 chars */
2086 if (endc
> startc
+ 256)
2087 EMSG_RET_NULL(_(e_invrange
));
2088 while (++startc
<= endc
)
2095 int alpha_only
= FALSE
;
2097 /* for alphabetical range skip the gaps
2098 * 'i'-'j', 'r'-'s', 'I'-'J' and 'R'-'S'. */
2099 if (isalpha(startc
) && isalpha(endc
))
2102 while (++startc
<= endc
)
2104 if (!alpha_only
|| isalpha(startc
))
2112 * Only "\]", "\^", "\]" and "\\" are special in Vi. Vim
2113 * accepts "\t", "\e", etc., but only when the 'l' flag in
2114 * 'cpoptions' is not included.
2115 * Posix doesn't recognize backslash at all.
2117 else if (*regparse
== '\\'
2119 && (vim_strchr(REGEXP_INRANGE
, regparse
[1]) != NULL
2121 && vim_strchr(REGEXP_ABBR
,
2122 regparse
[1]) != NULL
)))
2125 if (*regparse
== 'n')
2127 /* '\n' in range: also match NL */
2128 if (ret
!= JUST_CALC_SIZE
)
2131 *ret
= ANYBUT
+ ADD_NL
;
2132 else if (*ret
== ANYOF
)
2133 *ret
= ANYOF
+ ADD_NL
;
2134 /* else: must have had a \n already */
2140 else if (*regparse
== 'd'
2144 || *regparse
== 'U')
2146 startc
= coll_get_char();
2158 startc
= backslash_trans(*regparse
++);
2162 else if (*regparse
== '[')
2167 c_class
= get_char_class(®parse
);
2169 /* Characters assumed to be 8 bits! */
2173 c_class
= get_equi_class(®parse
);
2176 /* produce equivalence class */
2177 reg_equi_class(c_class
);
2180 get_coll_element(®parse
)) != 0)
2182 /* produce a collating element */
2187 /* literal '[', allow [[-x] as a range */
2188 startc
= *regparse
++;
2193 for (cu
= 1; cu
<= 255; cu
++)
2198 for (cu
= 1; cu
<= 255; cu
++)
2207 for (cu
= 1; cu
<= 255; cu
++)
2212 for (cu
= 1; cu
<= 255; cu
++)
2213 if (VIM_ISDIGIT(cu
))
2217 for (cu
= 1; cu
<= 255; cu
++)
2222 for (cu
= 1; cu
<= 255; cu
++)
2227 for (cu
= 1; cu
<= 255; cu
++)
2228 if (vim_isprintc(cu
))
2232 for (cu
= 1; cu
<= 255; cu
++)
2237 for (cu
= 9; cu
<= 13; cu
++)
2242 for (cu
= 1; cu
<= 255; cu
++)
2247 for (cu
= 1; cu
<= 255; cu
++)
2248 if (vim_isxdigit(cu
))
2257 case CLASS_BACKSPACE
:
2272 /* produce a multibyte character, including any
2273 * following composing characters */
2274 startc
= mb_ptr2char(regparse
);
2275 len
= (*mb_ptr2len
)(regparse
);
2276 if (enc_utf8
&& utf_char2len(startc
) != len
)
2277 startc
= -1; /* composing chars */
2284 startc
= *regparse
++;
2290 prevchr_len
= 1; /* last char was the ']' */
2291 if (*regparse
!= ']')
2292 EMSG_RET_NULL(_(e_toomsbra
)); /* Cannot happen? */
2293 skipchr(); /* let's be friends with the lexer again */
2294 *flagp
|= HASWIDTH
| SIMPLE
;
2297 else if (reg_strict
)
2298 EMSG_M_RET_NULL(_("E769: Missing ] after %s["),
2299 reg_magic
> MAGIC_OFF
);
2308 /* A multi-byte character is handled as a separate atom if it's
2309 * before a multi and when it's a composing char. */
2310 if (use_multibytecode(c
))
2313 ret
= regnode(MULTIBYTECODE
);
2315 *flagp
|= HASWIDTH
| SIMPLE
;
2320 ret
= regnode(EXACTLY
);
2323 * Append characters as long as:
2324 * - there is no following multi, we then need the character in
2325 * front of it as a single character operand
2326 * - not running into a Magic character
2327 * - "one_exactly" is not set
2328 * But always emit at least one character. Might be a Multi,
2329 * e.g., a "[" without matching "]".
2331 for (len
= 0; c
!= NUL
&& (len
== 0
2332 || (re_multi_type(peekchr()) == NOT_MULTI
2334 && !is_Magic(c
))); ++len
)
2345 /* Need to get composing character too. */
2348 l
= utf_ptr2len(regparse
);
2349 if (!UTF_COMPOSINGLIKE(regparse
, regparse
+ l
))
2351 regmbc(utf_ptr2char(regparse
));
2376 * Return TRUE if MULTIBYTECODE should be used instead of EXACTLY for
2380 use_multibytecode(c
)
2383 return has_mbyte
&& (*mb_char2len
)(c
) > 1
2384 && (re_multi_type(peekchr()) != NOT_MULTI
2385 || (enc_utf8
&& utf_iscomposing(c
)));
2391 * Return pointer to generated code.
2400 if (ret
== JUST_CALC_SIZE
)
2405 *regcode
++ = NUL
; /* Null "next" pointer. */
2412 * Emit (if appropriate) a byte of code
2418 if (regcode
== JUST_CALC_SIZE
)
2426 * Emit (if appropriate) a multi-byte character of code
2432 if (regcode
== JUST_CALC_SIZE
)
2433 regsize
+= (*mb_char2len
)(c
);
2435 regcode
+= (*mb_char2bytes
)(c
, regcode
);
2440 * reginsert - insert an operator in front of already-emitted operand
2442 * Means relocating the operand.
2453 if (regcode
== JUST_CALC_SIZE
)
2464 place
= opnd
; /* Op node, where operand used to be. */
2471 * reginsert_limits - insert an operator in front of already-emitted operand.
2472 * The operator has the given limit values as operands. Also set next pointer.
2474 * Means relocating the operand.
2477 reginsert_limits(op
, minval
, maxval
, opnd
)
2487 if (regcode
== JUST_CALC_SIZE
)
2498 place
= opnd
; /* Op node, where operand used to be. */
2502 place
= re_put_long(place
, (long_u
)minval
);
2503 place
= re_put_long(place
, (long_u
)maxval
);
2504 regtail(opnd
, place
);
2508 * Write a long as four bytes at "p" and return pointer to the next char.
2515 *p
++ = (char_u
) ((val
>> 24) & 0377);
2516 *p
++ = (char_u
) ((val
>> 16) & 0377);
2517 *p
++ = (char_u
) ((val
>> 8) & 0377);
2518 *p
++ = (char_u
) (val
& 0377);
2523 * regtail - set the next-pointer at the end of a node chain
2534 if (p
== JUST_CALC_SIZE
)
2537 /* Find last node. */
2541 temp
= regnext(scan
);
2547 if (OP(scan
) == BACK
)
2548 offset
= (int)(scan
- val
);
2550 offset
= (int)(val
- scan
);
2551 *(scan
+ 1) = (char_u
) (((unsigned)offset
>> 8) & 0377);
2552 *(scan
+ 2) = (char_u
) (offset
& 0377);
2556 * regoptail - regtail on item after a BRANCH; nop if none
2563 /* When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless" */
2564 if (p
== NULL
|| p
== JUST_CALC_SIZE
2566 && (OP(p
) < BRACE_COMPLEX
|| OP(p
) > BRACE_COMPLEX
+ 9)))
2568 regtail(OPERAND(p
), val
);
2572 * getchr() - get the next character from the pattern. We know about
2573 * magic and such, so therefore we need a lexical analyzer.
2576 /* static int curchr; */
2577 static int prevprevchr
;
2579 static int nextchr
; /* used for ungetchr() */
2581 * Note: prevchr is sometimes -1 when we are not at the start,
2582 * eg in /[ ^I]^ the pattern was never found even if it existed, because ^ was
2583 * taken to be magic -- webb
2585 static int at_start
; /* True when on the first character */
2586 static int prev_at_start
; /* True when on the second character */
2594 curchr
= prevprevchr
= prevchr
= nextchr
= -1;
2596 prev_at_start
= FALSE
;
2602 static int after_slash
= FALSE
;
2606 switch (curchr
= regparse
[0])
2611 /* magic when 'magic' is on */
2612 if (reg_magic
>= MAGIC_ON
)
2613 curchr
= Magic(curchr
);
2628 case '#': /* future ext. */
2629 case '"': /* future ext. */
2630 case '\'': /* future ext. */
2631 case ',': /* future ext. */
2632 case '-': /* future ext. */
2633 case ':': /* future ext. */
2634 case ';': /* future ext. */
2635 case '`': /* future ext. */
2636 case '/': /* Can't be used in / command */
2637 /* magic only after "\v" */
2638 if (reg_magic
== MAGIC_ALL
)
2639 curchr
= Magic(curchr
);
2642 /* * is not magic as the very first character, eg "?*ptr", when
2643 * after '^', eg "/^*ptr" and when after "\(", "\|", "\&". But
2644 * "\(\*" is not magic, thus must be magic if "after_slash" */
2645 if (reg_magic
>= MAGIC_ON
2647 && !(prev_at_start
&& prevchr
== Magic('^'))
2649 || (prevchr
!= Magic('(')
2650 && prevchr
!= Magic('&')
2651 && prevchr
!= Magic('|'))))
2652 curchr
= Magic('*');
2655 /* '^' is only magic as the very first character and if it's after
2656 * "\(", "\|", "\&' or "\n" */
2657 if (reg_magic
>= MAGIC_OFF
2659 || reg_magic
== MAGIC_ALL
2660 || prevchr
== Magic('(')
2661 || prevchr
== Magic('|')
2662 || prevchr
== Magic('&')
2663 || prevchr
== Magic('n')
2664 || (no_Magic(prevchr
) == '('
2665 && prevprevchr
== Magic('%'))))
2667 curchr
= Magic('^');
2669 prev_at_start
= FALSE
;
2673 /* '$' is only magic as the very last char and if it's in front of
2674 * either "\|", "\)", "\&", or "\n" */
2675 if (reg_magic
>= MAGIC_OFF
)
2677 char_u
*p
= regparse
+ 1;
2679 /* ignore \c \C \m and \M after '$' */
2680 while (p
[0] == '\\' && (p
[1] == 'c' || p
[1] == 'C'
2681 || p
[1] == 'm' || p
[1] == 'M' || p
[1] == 'Z'))
2685 && (p
[1] == '|' || p
[1] == '&' || p
[1] == ')'
2687 || reg_magic
== MAGIC_ALL
)
2688 curchr
= Magic('$');
2693 int c
= regparse
[1];
2696 curchr
= '\\'; /* trailing '\' */
2701 c
<= '~' && META_flags
[c
]
2706 * META contains everything that may be magic sometimes,
2707 * except ^ and $ ("\^" and "\$" are only magic after
2708 * "\v"). We now fetch the next character and toggle its
2709 * magicness. Therefore, \ is so meta-magic that it is
2713 prev_at_start
= at_start
;
2714 at_start
= FALSE
; /* be able to say "/\*ptr" */
2720 curchr
= toggle_Magic(curchr
);
2722 else if (vim_strchr(REGEXP_ABBR
, c
))
2725 * Handle abbreviations, like "\t" for TAB -- webb
2727 curchr
= backslash_trans(c
);
2729 else if (reg_magic
== MAGIC_NONE
&& (c
== '$' || c
== '^'))
2730 curchr
= toggle_Magic(c
);
2734 * Next character can never be (made) magic?
2735 * Then backslashing it won't do anything.
2739 curchr
= (*mb_ptr2char
)(regparse
+ 1);
2750 curchr
= (*mb_ptr2char
)(regparse
);
2759 * Eat one lexed character. Do this in a way that we can undo it.
2764 /* peekchr() eats a backslash, do the same here */
2765 if (*regparse
== '\\')
2769 if (regparse
[prevchr_len
] != NUL
)
2773 prevchr_len
+= utf_char2len(mb_ptr2char(regparse
+ prevchr_len
));
2775 prevchr_len
+= (*mb_ptr2len
)(regparse
+ prevchr_len
);
2780 regparse
+= prevchr_len
;
2781 prev_at_start
= at_start
;
2783 prevprevchr
= prevchr
;
2785 curchr
= nextchr
; /* use previously unget char, or -1 */
2790 * Skip a character while keeping the value of prev_at_start for at_start.
2791 * prevchr and prevprevchr are also kept.
2796 int as
= prev_at_start
;
2798 int prpr
= prevprevchr
;
2809 int chr
= peekchr();
2816 * put character back. Works only once!
2823 prevchr
= prevprevchr
;
2824 at_start
= prev_at_start
;
2825 prev_at_start
= FALSE
;
2827 /* Backup regparse, so that it's at the same position as before the
2829 regparse
-= prevchr_len
;
2833 * Get and return the value of the hex string at the current position.
2834 * Return -1 if there is no valid hex number.
2835 * The position is updated:
2838 * The parameter controls the maximum number of input characters. This will be
2839 * 2 when reading a \%x20 sequence and 4 when reading a \%u20AC sequence.
2842 gethexchrs(maxinputlen
)
2849 for (i
= 0; i
< maxinputlen
; ++i
)
2852 if (!vim_isxdigit(c
))
2865 * get and return the value of the decimal string immediately after the
2866 * current position. Return -1 for invalid. Consumes all digits.
2878 if (c
< '0' || c
> '9')
2891 * get and return the value of the octal string immediately after the current
2892 * position. Return -1 for invalid, or 0-255 for valid. Smart enough to handle
2893 * numbers > 377 correctly (for example, 400 is treated as 40) and doesn't
2894 * treat 8 or 9 as recognised characters. Position is updated:
2895 * blahblah\%o210asdf
2905 for (i
= 0; i
< 3 && nr
< 040; ++i
)
2908 if (c
< '0' || c
> '7')
2921 * Get a number after a backslash that is inside [].
2922 * When nothing is recognized return a backslash.
2929 switch (*regparse
++)
2931 case 'd': nr
= getdecchrs(); break;
2932 case 'o': nr
= getoctchrs(); break;
2933 case 'x': nr
= gethexchrs(2); break;
2934 case 'u': nr
= gethexchrs(4); break;
2935 case 'U': nr
= gethexchrs(8); break;
2939 /* If getting the number fails be backwards compatible: the character
2940 * is a backslash. */
2948 * read_limits - Read two integers to be taken as a minimum and maximum.
2949 * If the first character is '-', then the range is reversed.
2950 * Should end with 'end'. If minval is missing, zero is default, if maxval is
2951 * missing, a very big number is the default.
2954 read_limits(minval
, maxval
)
2958 int reverse
= FALSE
;
2962 if (*regparse
== '-')
2964 /* Starts with '-', so reverse the range later */
2968 first_char
= regparse
;
2969 *minval
= getdigits(®parse
);
2970 if (*regparse
== ',') /* There is a comma */
2972 if (vim_isdigit(*++regparse
))
2973 *maxval
= getdigits(®parse
);
2975 *maxval
= MAX_LIMIT
;
2977 else if (VIM_ISDIGIT(*first_char
))
2978 *maxval
= *minval
; /* It was \{n} or \{-n} */
2980 *maxval
= MAX_LIMIT
; /* It was \{} or \{-} */
2981 if (*regparse
== '\\')
2982 regparse
++; /* Allow either \{...} or \{...\} */
2983 if (*regparse
!= '}')
2985 sprintf((char *)IObuff
, _("E554: Syntax error in %s{...}"),
2986 reg_magic
== MAGIC_ALL
? "" : "\\");
2987 EMSG_RET_FAIL(IObuff
);
2991 * Reverse the range if there was a '-', or make sure it is in the right
2994 if ((!reverse
&& *minval
> *maxval
) || (reverse
&& *minval
< *maxval
))
3000 skipchr(); /* let's be friends with the lexer again */
3005 * vim_regexec and friends
3009 * Global work variables for vim_regexec().
3012 /* The current match-position is remembered with these variables: */
3013 static linenr_T reglnum
; /* line number, relative to first line */
3014 static char_u
*regline
; /* start of current line */
3015 static char_u
*reginput
; /* current input, points into "regline" */
3017 static int need_clear_subexpr
; /* subexpressions still need to be
3020 static int need_clear_zsubexpr
= FALSE
; /* extmatch subexpressions
3021 * still need to be cleared */
3025 * Structure used to save the current input state, when it needs to be
3026 * restored after trying a match. Used by reg_save() and reg_restore().
3027 * Also stores the length of "backpos".
3033 char_u
*ptr
; /* reginput pointer, for single-line regexp */
3034 lpos_T pos
; /* reginput pos, for multi-line regexp */
3039 /* struct to save start/end pointer/position in for \(\) */
3049 static char_u
*reg_getline
__ARGS((linenr_T lnum
));
3050 static long vim_regexec_both
__ARGS((char_u
*line
, colnr_T col
));
3051 static long regtry
__ARGS((regprog_T
*prog
, colnr_T col
));
3052 static void cleanup_subexpr
__ARGS((void));
3054 static void cleanup_zsubexpr
__ARGS((void));
3056 static void reg_nextline
__ARGS((void));
3057 static void reg_save
__ARGS((regsave_T
*save
, garray_T
*gap
));
3058 static void reg_restore
__ARGS((regsave_T
*save
, garray_T
*gap
));
3059 static int reg_save_equal
__ARGS((regsave_T
*save
));
3060 static void save_se_multi
__ARGS((save_se_T
*savep
, lpos_T
*posp
));
3061 static void save_se_one
__ARGS((save_se_T
*savep
, char_u
**pp
));
3063 /* Save the sub-expressions before attempting a match. */
3064 #define save_se(savep, posp, pp) \
3065 REG_MULTI ? save_se_multi((savep), (posp)) : save_se_one((savep), (pp))
3067 /* After a failed match restore the sub-expressions. */
3068 #define restore_se(savep, posp, pp) { \
3070 *(posp) = (savep)->se_u.pos; \
3072 *(pp) = (savep)->se_u.ptr; }
3074 static int re_num_cmp
__ARGS((long_u val
, char_u
*scan
));
3075 static int regmatch
__ARGS((char_u
*prog
));
3076 static int regrepeat
__ARGS((char_u
*p
, long maxcount
));
3083 * Internal copy of 'ignorecase'. It is set at each call to vim_regexec().
3084 * Normally it gets the value of "rm_ic" or "rmm_ic", but when the pattern
3085 * contains '\c' or '\C' the value is overruled.
3091 * Similar to ireg_ic, but only for 'combining' characters. Set with \Z flag
3092 * in the regexp. Defaults to false, always.
3094 static int ireg_icombine
;
3098 * Copy of "rmm_maxcol": maximum column to search for a match. Zero when
3099 * there is no maximum.
3101 static colnr_T ireg_maxcol
;
3104 * Sometimes need to save a copy of a line. Since alloc()/free() is very
3105 * slow, we keep one allocated piece of memory and only re-allocate it when
3106 * it's too small. It's freed in vim_regexec_both() when finished.
3108 static char_u
*reg_tofree
;
3109 static unsigned reg_tofreelen
;
3112 * These variables are set when executing a regexp to speed up the execution.
3113 * Which ones are set depends on whethere a single-line or multi-line match is
3115 * single-line multi-line
3116 * reg_match ®match_T NULL
3117 * reg_mmatch NULL ®mmatch_T
3118 * reg_startp reg_match->startp <invalid>
3119 * reg_endp reg_match->endp <invalid>
3120 * reg_startpos <invalid> reg_mmatch->startpos
3121 * reg_endpos <invalid> reg_mmatch->endpos
3122 * reg_win NULL window in which to search
3123 * reg_buf <invalid> buffer in which to search
3124 * reg_firstlnum <invalid> first line in which to search
3125 * reg_maxline 0 last line nr
3126 * reg_line_lbr FALSE or TRUE FALSE
3128 static regmatch_T
*reg_match
;
3129 static regmmatch_T
*reg_mmatch
;
3130 static char_u
**reg_startp
= NULL
;
3131 static char_u
**reg_endp
= NULL
;
3132 static lpos_T
*reg_startpos
= NULL
;
3133 static lpos_T
*reg_endpos
= NULL
;
3134 static win_T
*reg_win
;
3135 static buf_T
*reg_buf
;
3136 static linenr_T reg_firstlnum
;
3137 static linenr_T reg_maxline
;
3138 static int reg_line_lbr
; /* "\n" in string is line break */
3140 /* Values for rs_state in regitem_T. */
3141 typedef enum regstate_E
3143 RS_NOPEN
= 0 /* NOPEN and NCLOSE */
3144 , RS_MOPEN
/* MOPEN + [0-9] */
3145 , RS_MCLOSE
/* MCLOSE + [0-9] */
3147 , RS_ZOPEN
/* ZOPEN + [0-9] */
3148 , RS_ZCLOSE
/* ZCLOSE + [0-9] */
3150 , RS_BRANCH
/* BRANCH */
3151 , RS_BRCPLX_MORE
/* BRACE_COMPLEX and trying one more match */
3152 , RS_BRCPLX_LONG
/* BRACE_COMPLEX and trying longest match */
3153 , RS_BRCPLX_SHORT
/* BRACE_COMPLEX and trying shortest match */
3154 , RS_NOMATCH
/* NOMATCH */
3155 , RS_BEHIND1
/* BEHIND / NOBEHIND matching rest */
3156 , RS_BEHIND2
/* BEHIND / NOBEHIND matching behind part */
3157 , RS_STAR_LONG
/* STAR/PLUS/BRACE_SIMPLE longest match */
3158 , RS_STAR_SHORT
/* STAR/PLUS/BRACE_SIMPLE shortest match */
3162 * When there are alternatives a regstate_T is put on the regstack to remember
3163 * what we are doing.
3164 * Before it may be another type of item, depending on rs_state, to remember
3167 typedef struct regitem_S
3169 regstate_T rs_state
; /* what we are doing, one of RS_ above */
3170 char_u
*rs_scan
; /* current node in program */
3175 } rs_un
; /* room for saving reginput */
3176 short rs_no
; /* submatch nr */
3179 static regitem_T
*regstack_push
__ARGS((regstate_T state
, char_u
*scan
));
3180 static void regstack_pop
__ARGS((char_u
**scan
));
3182 /* used for BEHIND and NOBEHIND matching */
3183 typedef struct regbehind_S
3185 regsave_T save_after
;
3186 regsave_T save_behind
;
3189 /* used for STAR, PLUS and BRACE_SIMPLE matching */
3190 typedef struct regstar_S
3192 int nextb
; /* next byte */
3193 int nextb_ic
; /* next byte reverse case */
3199 /* used to store input position when a BACK was encountered, so that we now if
3200 * we made any progress since the last time. */
3201 typedef struct backpos_S
3203 char_u
*bp_scan
; /* "scan" where BACK was encountered */
3204 regsave_T bp_pos
; /* last input position */
3208 * regstack and backpos are used by regmatch(). They are kept over calls to
3209 * avoid invoking malloc() and free() often.
3211 static garray_T regstack
; /* stack with regitem_T items, sometimes
3212 preceded by regstar_T or regbehind_T. */
3213 static garray_T backpos
; /* table with backpos_T for BACK */
3216 * Get pointer to the line "lnum", which is relative to "reg_firstlnum".
3222 /* when looking behind for a match/no-match lnum is negative. But we
3223 * can't go before line 1 */
3224 if (reg_firstlnum
+ lnum
< 1)
3226 if (lnum
> reg_maxline
)
3227 /* Must have matched the "\n" in the last line. */
3228 return (char_u
*)"";
3229 return ml_get_buf(reg_buf
, reg_firstlnum
+ lnum
, FALSE
);
3232 static regsave_T behind_pos
;
3235 static char_u
*reg_startzp
[NSUBEXP
]; /* Workspace to mark beginning */
3236 static char_u
*reg_endzp
[NSUBEXP
]; /* and end of \z(...\) matches */
3237 static lpos_T reg_startzpos
[NSUBEXP
]; /* idem, beginning pos */
3238 static lpos_T reg_endzpos
[NSUBEXP
]; /* idem, end pos */
3241 /* TRUE if using multi-line regexp. */
3242 #define REG_MULTI (reg_match == NULL)
3245 * Match a regexp against a string.
3246 * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
3247 * Uses curbuf for line count and 'iskeyword'.
3249 * Return TRUE if there is a match, FALSE if not.
3252 vim_regexec(rmp
, line
, col
)
3254 char_u
*line
; /* string to match against */
3255 colnr_T col
; /* column to start looking for match */
3260 reg_line_lbr
= FALSE
;
3262 ireg_ic
= rmp
->rm_ic
;
3264 ireg_icombine
= FALSE
;
3267 return (vim_regexec_both(line
, col
) != 0);
3270 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) \
3271 || defined(FIND_REPLACE_DIALOG) || defined(PROTO)
3273 * Like vim_regexec(), but consider a "\n" in "line" to be a line break.
3276 vim_regexec_nl(rmp
, line
, col
)
3278 char_u
*line
; /* string to match against */
3279 colnr_T col
; /* column to start looking for match */
3284 reg_line_lbr
= TRUE
;
3286 ireg_ic
= rmp
->rm_ic
;
3288 ireg_icombine
= FALSE
;
3291 return (vim_regexec_both(line
, col
) != 0);
3296 * Match a regexp against multiple lines.
3297 * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
3298 * Uses curbuf for line count and 'iskeyword'.
3300 * Return zero if there is no match. Return number of lines contained in the
3304 vim_regexec_multi(rmp
, win
, buf
, lnum
, col
)
3306 win_T
*win
; /* window in which to search or NULL */
3307 buf_T
*buf
; /* buffer in which to search */
3308 linenr_T lnum
; /* nr of line to start looking for match */
3309 colnr_T col
; /* column to start looking for match */
3312 buf_T
*save_curbuf
= curbuf
;
3318 reg_firstlnum
= lnum
;
3319 reg_maxline
= reg_buf
->b_ml
.ml_line_count
- lnum
;
3320 reg_line_lbr
= FALSE
;
3321 ireg_ic
= rmp
->rmm_ic
;
3323 ireg_icombine
= FALSE
;
3325 ireg_maxcol
= rmp
->rmm_maxcol
;
3327 /* Need to switch to buffer "buf" to make vim_iswordc() work. */
3329 r
= vim_regexec_both(NULL
, col
);
3330 curbuf
= save_curbuf
;
3336 * Match a regexp against a string ("line" points to the string) or multiple
3337 * lines ("line" is NULL, use reg_getline()).
3340 vim_regexec_both(line
, col
)
3342 colnr_T col
; /* column to start looking for match */
3350 /* Init the regstack empty. Use an item size of 1 byte, since we push
3351 * different things onto it. Use a large grow size to avoid reallocating
3353 ga_init2(®stack
, 1, 10000);
3355 /* Init the backpos table empty. */
3356 ga_init2(&backpos
, sizeof(backpos_T
), 10);
3360 prog
= reg_mmatch
->regprog
;
3361 line
= reg_getline((linenr_T
)0);
3362 reg_startpos
= reg_mmatch
->startpos
;
3363 reg_endpos
= reg_mmatch
->endpos
;
3367 prog
= reg_match
->regprog
;
3368 reg_startp
= reg_match
->startp
;
3369 reg_endp
= reg_match
->endp
;
3372 /* Be paranoid... */
3373 if (prog
== NULL
|| line
== NULL
)
3379 /* Check validity of program. */
3380 if (prog_magic_wrong())
3383 /* If the start column is past the maximum column: no need to try. */
3384 if (ireg_maxcol
> 0 && col
>= ireg_maxcol
)
3387 /* If pattern contains "\c" or "\C": overrule value of ireg_ic */
3388 if (prog
->regflags
& RF_ICASE
)
3390 else if (prog
->regflags
& RF_NOICASE
)
3394 /* If pattern contains "\Z" overrule value of ireg_icombine */
3395 if (prog
->regflags
& RF_ICOMBINE
)
3396 ireg_icombine
= TRUE
;
3399 /* If there is a "must appear" string, look for it. */
3400 if (prog
->regmust
!= NULL
)
3406 c
= (*mb_ptr2char
)(prog
->regmust
);
3413 * This is used very often, esp. for ":global". Use three versions of
3414 * the loop to avoid overhead of conditions.
3421 while ((s
= vim_strbyte(s
, c
)) != NULL
)
3423 if (cstrncmp(s
, prog
->regmust
, &prog
->regmlen
) == 0)
3424 break; /* Found it. */
3428 else if (!ireg_ic
|| (!enc_utf8
&& mb_char2len(c
) > 1))
3429 while ((s
= vim_strchr(s
, c
)) != NULL
)
3431 if (cstrncmp(s
, prog
->regmust
, &prog
->regmlen
) == 0)
3432 break; /* Found it. */
3437 while ((s
= cstrchr(s
, c
)) != NULL
)
3439 if (cstrncmp(s
, prog
->regmust
, &prog
->regmlen
) == 0)
3440 break; /* Found it. */
3443 if (s
== NULL
) /* Not present. */
3450 /* Simplest case: Anchored match need be tried only once. */
3457 c
= (*mb_ptr2char
)(regline
+ col
);
3461 if (prog
->regstart
== NUL
3462 || prog
->regstart
== c
3465 (enc_utf8
&& utf_fold(prog
->regstart
) == utf_fold(c
)))
3466 || (c
< 255 && prog
->regstart
< 255 &&
3468 TOLOWER_LOC(prog
->regstart
) == TOLOWER_LOC(c
)))))
3469 retval
= regtry(prog
, col
);
3475 /* Messy cases: unanchored match. */
3478 if (prog
->regstart
!= NUL
)
3480 /* Skip until the char we know it must start with.
3481 * Used often, do some work to avoid call overhead. */
3487 s
= vim_strbyte(regline
+ col
, prog
->regstart
);
3489 s
= cstrchr(regline
+ col
, prog
->regstart
);
3495 col
= (int)(s
- regline
);
3498 /* Check for maximum column to try. */
3499 if (ireg_maxcol
> 0 && col
>= ireg_maxcol
)
3505 retval
= regtry(prog
, col
);
3509 /* if not currently on the first line, get it again */
3513 regline
= reg_getline((linenr_T
)0);
3515 if (regline
[col
] == NUL
)
3519 col
+= (*mb_ptr2len
)(regline
+ col
);
3527 vim_free(reg_tofree
);
3528 ga_clear(®stack
);
3535 static reg_extmatch_T
*make_extmatch
__ARGS((void));
3538 * Create a new extmatch and mark it as referenced once.
3540 static reg_extmatch_T
*
3545 em
= (reg_extmatch_T
*)alloc_clear((unsigned)sizeof(reg_extmatch_T
));
3552 * Add a reference to an extmatch.
3564 * Remove a reference to an extmatch. If there are no references left, free
3573 if (em
!= NULL
&& --em
->refcnt
<= 0)
3575 for (i
= 0; i
< NSUBEXP
; ++i
)
3576 vim_free(em
->matches
[i
]);
3583 * regtry - try match of "prog" with at regline["col"].
3584 * Returns 0 for failure, number of lines contained in the match otherwise.
3591 reginput
= regline
+ col
;
3592 need_clear_subexpr
= TRUE
;
3594 /* Clear the external match subpointers if necessary. */
3595 if (prog
->reghasz
== REX_SET
)
3596 need_clear_zsubexpr
= TRUE
;
3599 if (regmatch(prog
->program
+ 1) == 0)
3605 if (reg_startpos
[0].lnum
< 0)
3607 reg_startpos
[0].lnum
= 0;
3608 reg_startpos
[0].col
= col
;
3610 if (reg_endpos
[0].lnum
< 0)
3612 reg_endpos
[0].lnum
= reglnum
;
3613 reg_endpos
[0].col
= (int)(reginput
- regline
);
3616 /* Use line number of "\ze". */
3617 reglnum
= reg_endpos
[0].lnum
;
3621 if (reg_startp
[0] == NULL
)
3622 reg_startp
[0] = regline
+ col
;
3623 if (reg_endp
[0] == NULL
)
3624 reg_endp
[0] = reginput
;
3627 /* Package any found \z(...\) matches for export. Default is none. */
3628 unref_extmatch(re_extmatch_out
);
3629 re_extmatch_out
= NULL
;
3631 if (prog
->reghasz
== REX_SET
)
3636 re_extmatch_out
= make_extmatch();
3637 for (i
= 0; i
< NSUBEXP
; i
++)
3641 /* Only accept single line matches. */
3642 if (reg_startzpos
[i
].lnum
>= 0
3643 && reg_endzpos
[i
].lnum
== reg_startzpos
[i
].lnum
)
3644 re_extmatch_out
->matches
[i
] =
3645 vim_strnsave(reg_getline(reg_startzpos
[i
].lnum
)
3646 + reg_startzpos
[i
].col
,
3647 reg_endzpos
[i
].col
- reg_startzpos
[i
].col
);
3651 if (reg_startzp
[i
] != NULL
&& reg_endzp
[i
] != NULL
)
3652 re_extmatch_out
->matches
[i
] =
3653 vim_strnsave(reg_startzp
[i
],
3654 (int)(reg_endzp
[i
] - reg_startzp
[i
]));
3663 static int reg_prev_class
__ARGS((void));
3666 * Get class of previous character.
3671 if (reginput
> regline
)
3672 return mb_get_class(reginput
- 1
3673 - (*mb_head_off
)(regline
, reginput
- 1));
3678 #define ADVANCE_REGINPUT() mb_ptr_adv(reginput)
3681 * The arguments from BRACE_LIMITS are stored here. They are actually local
3682 * to regmatch(), but they are here to reduce the amount of stack space used
3683 * (it can be called recursively many times).
3685 static long bl_minval
;
3686 static long bl_maxval
;
3689 * regmatch - main matching routine
3691 * Conceptually the strategy is simple: Check to see whether the current node
3692 * matches, push an item onto the regstack and loop to see whether the rest
3693 * matches, and then act accordingly. In practice we make some effort to
3694 * avoid using the regstack, in particular by going through "ordinary" nodes
3695 * (that don't need to know whether the rest of the match failed) by a nested
3698 * Returns TRUE when there is a match. Leaves reginput and reglnum just after
3699 * the last matched character.
3700 * Returns FALSE when there is no match. Leaves reginput and reglnum in an
3705 char_u
*scan
; /* Current node. */
3707 char_u
*next
; /* Next node. */
3712 int status
; /* one of the RA_ values: */
3713 #define RA_FAIL 1 /* something failed, abort */
3714 #define RA_CONT 2 /* continue in inner loop */
3715 #define RA_BREAK 3 /* break inner loop */
3716 #define RA_MATCH 4 /* successful match */
3717 #define RA_NOMATCH 5 /* didn't match */
3719 /* Init the regstack and backpos table empty. They are initialized and
3720 * freed in vim_regexec_both() to reduce malloc()/free() calls. */
3721 regstack
.ga_len
= 0;
3725 * Repeat until "regstack" is empty.
3729 /* Some patterns my cause a long time to match, even though they are not
3730 * illegal. E.g., "\([a-z]\+\)\+Q". Allow breaking them with CTRL-C. */
3734 if (scan
!= NULL
&& regnarrate
)
3736 mch_errmsg(regprop(scan
));
3742 * Repeat for items that can be matched sequentially, without using the
3747 if (got_int
|| scan
== NULL
)
3757 mch_errmsg(regprop(scan
));
3758 mch_errmsg("...\n");
3760 if (re_extmatch_in
!= NULL
)
3764 mch_errmsg(_("External submatches:\n"));
3765 for (i
= 0; i
< NSUBEXP
; i
++)
3768 if (re_extmatch_in
->matches
[i
] != NULL
)
3769 mch_errmsg(re_extmatch_in
->matches
[i
]);
3776 next
= regnext(scan
);
3779 /* Check for character class with NL added. */
3780 if (!reg_line_lbr
&& WITH_NL(op
) && REG_MULTI
3781 && *reginput
== NUL
&& reglnum
<= reg_maxline
)
3785 else if (reg_line_lbr
&& WITH_NL(op
) && *reginput
== '\n')
3795 c
= (*mb_ptr2char
)(reginput
);
3802 if (reginput
!= regline
)
3803 status
= RA_NOMATCH
;
3808 status
= RA_NOMATCH
;
3812 /* Passing -1 to the getline() function provided for the search
3813 * should always return NULL if the current line is the first
3814 * line of the file. */
3815 if (reglnum
!= 0 || reginput
!= regline
3816 || (REG_MULTI
&& reg_getline((linenr_T
)-1) != NULL
))
3817 status
= RA_NOMATCH
;
3821 if (reglnum
!= reg_maxline
|| c
!= NUL
)
3822 status
= RA_NOMATCH
;
3826 /* Check if the buffer is in a window and compare the
3827 * reg_win->w_cursor position to the match position. */
3829 || (reglnum
+ reg_firstlnum
!= reg_win
->w_cursor
.lnum
)
3830 || ((colnr_T
)(reginput
- regline
) != reg_win
->w_cursor
.col
))
3831 status
= RA_NOMATCH
;
3835 /* Compare the mark position to the match position. NOTE: Always
3836 * uses the current buffer. */
3838 int mark
= OPERAND(scan
)[0];
3839 int cmp
= OPERAND(scan
)[1];
3842 pos
= getmark(mark
, FALSE
);
3843 if (pos
== NULL
/* mark doesn't exist) */
3844 || pos
->lnum
<= 0 /* mark isn't set (in curbuf) */
3845 || (pos
->lnum
== reglnum
+ reg_firstlnum
3846 ? (pos
->col
== (colnr_T
)(reginput
- regline
)
3847 ? (cmp
== '<' || cmp
== '>')
3848 : (pos
->col
< (colnr_T
)(reginput
- regline
)
3851 : (pos
->lnum
< reglnum
+ reg_firstlnum
3854 status
= RA_NOMATCH
;
3860 /* Check if the buffer is the current buffer. and whether the
3861 * position is inside the Visual area. */
3862 if (reg_buf
!= curbuf
|| VIsual
.lnum
== 0)
3863 status
= RA_NOMATCH
;
3869 win_T
*wp
= reg_win
== NULL
? curwin
: reg_win
;
3874 if (lt(VIsual
, wp
->w_cursor
))
3888 if (lt(curbuf
->b_visual
.vi_start
, curbuf
->b_visual
.vi_end
))
3890 top
= curbuf
->b_visual
.vi_start
;
3891 bot
= curbuf
->b_visual
.vi_end
;
3895 top
= curbuf
->b_visual
.vi_end
;
3896 bot
= curbuf
->b_visual
.vi_start
;
3898 mode
= curbuf
->b_visual
.vi_mode
;
3900 lnum
= reglnum
+ reg_firstlnum
;
3901 col
= (colnr_T
)(reginput
- regline
);
3902 if (lnum
< top
.lnum
|| lnum
> bot
.lnum
)
3903 status
= RA_NOMATCH
;
3904 else if (mode
== 'v')
3906 if ((lnum
== top
.lnum
&& col
< top
.col
)
3907 || (lnum
== bot
.lnum
3908 && col
>= bot
.col
+ (*p_sel
!= 'e')))
3909 status
= RA_NOMATCH
;
3911 else if (mode
== Ctrl_V
)
3914 colnr_T start2
, end2
;
3917 getvvcol(wp
, &top
, &start
, NULL
, &end
);
3918 getvvcol(wp
, &bot
, &start2
, NULL
, &end2
);
3923 if (top
.col
== MAXCOL
|| bot
.col
== MAXCOL
)
3925 cols
= win_linetabsize(wp
,
3926 regline
, (colnr_T
)(reginput
- regline
));
3927 if (cols
< start
|| cols
> end
- (*p_sel
== 'e'))
3928 status
= RA_NOMATCH
;
3932 status
= RA_NOMATCH
;
3937 if (!REG_MULTI
|| !re_num_cmp((long_u
)(reglnum
+ reg_firstlnum
),
3939 status
= RA_NOMATCH
;
3943 if (!re_num_cmp((long_u
)(reginput
- regline
) + 1, scan
))
3944 status
= RA_NOMATCH
;
3948 if (!re_num_cmp((long_u
)win_linetabsize(
3949 reg_win
== NULL
? curwin
: reg_win
,
3950 regline
, (colnr_T
)(reginput
- regline
)) + 1, scan
))
3951 status
= RA_NOMATCH
;
3954 case BOW
: /* \<word; reginput points to w */
3955 if (c
== NUL
) /* Can't match at end of line */
3956 status
= RA_NOMATCH
;
3962 /* Get class of current and previous char (if it exists). */
3963 this_class
= mb_get_class(reginput
);
3964 if (this_class
<= 1)
3965 status
= RA_NOMATCH
; /* not on a word at all */
3966 else if (reg_prev_class() == this_class
)
3967 status
= RA_NOMATCH
; /* previous char is in same word */
3973 || (reginput
> regline
&& vim_iswordc(reginput
[-1])))
3974 status
= RA_NOMATCH
;
3978 case EOW
: /* word\>; reginput points after d */
3979 if (reginput
== regline
) /* Can't match at start of line */
3980 status
= RA_NOMATCH
;
3984 int this_class
, prev_class
;
3986 /* Get class of current and previous char (if it exists). */
3987 this_class
= mb_get_class(reginput
);
3988 prev_class
= reg_prev_class();
3989 if (this_class
== prev_class
3990 || prev_class
== 0 || prev_class
== 1)
3991 status
= RA_NOMATCH
;
3996 if (!vim_iswordc(reginput
[-1])
3997 || (reginput
[0] != NUL
&& vim_iswordc(c
)))
3998 status
= RA_NOMATCH
;
4000 break; /* Matched with EOW */
4004 status
= RA_NOMATCH
;
4011 status
= RA_NOMATCH
;
4017 if (VIM_ISDIGIT(*reginput
) || !vim_isIDc(c
))
4018 status
= RA_NOMATCH
;
4024 if (!vim_iswordp(reginput
))
4025 status
= RA_NOMATCH
;
4031 if (VIM_ISDIGIT(*reginput
) || !vim_iswordp(reginput
))
4032 status
= RA_NOMATCH
;
4038 if (!vim_isfilec(c
))
4039 status
= RA_NOMATCH
;
4045 if (VIM_ISDIGIT(*reginput
) || !vim_isfilec(c
))
4046 status
= RA_NOMATCH
;
4052 if (ptr2cells(reginput
) != 1)
4053 status
= RA_NOMATCH
;
4059 if (VIM_ISDIGIT(*reginput
) || ptr2cells(reginput
) != 1)
4060 status
= RA_NOMATCH
;
4066 if (!vim_iswhite(c
))
4067 status
= RA_NOMATCH
;
4073 if (c
== NUL
|| vim_iswhite(c
))
4074 status
= RA_NOMATCH
;
4081 status
= RA_NOMATCH
;
4087 if (c
== NUL
|| ri_digit(c
))
4088 status
= RA_NOMATCH
;
4095 status
= RA_NOMATCH
;
4101 if (c
== NUL
|| ri_hex(c
))
4102 status
= RA_NOMATCH
;
4109 status
= RA_NOMATCH
;
4115 if (c
== NUL
|| ri_octal(c
))
4116 status
= RA_NOMATCH
;
4123 status
= RA_NOMATCH
;
4129 if (c
== NUL
|| ri_word(c
))
4130 status
= RA_NOMATCH
;
4137 status
= RA_NOMATCH
;
4143 if (c
== NUL
|| ri_head(c
))
4144 status
= RA_NOMATCH
;
4151 status
= RA_NOMATCH
;
4157 if (c
== NUL
|| ri_alpha(c
))
4158 status
= RA_NOMATCH
;
4165 status
= RA_NOMATCH
;
4171 if (c
== NUL
|| ri_lower(c
))
4172 status
= RA_NOMATCH
;
4179 status
= RA_NOMATCH
;
4185 if (c
== NUL
|| ri_upper(c
))
4186 status
= RA_NOMATCH
;
4196 opnd
= OPERAND(scan
);
4197 /* Inline the first byte, for speed. */
4198 if (*opnd
!= *reginput
4203 TOLOWER_LOC(*opnd
) != TOLOWER_LOC(*reginput
))))
4204 status
= RA_NOMATCH
;
4205 else if (*opnd
== NUL
)
4207 /* match empty string always works; happens when "~" is
4210 else if (opnd
[1] == NUL
4212 && !(enc_utf8
&& ireg_ic
)
4215 ++reginput
; /* matched a single char */
4218 len
= (int)STRLEN(opnd
);
4219 /* Need to match first byte again for multi-byte. */
4220 if (cstrncmp(opnd
, reginput
, &len
) != 0)
4221 status
= RA_NOMATCH
;
4223 /* Check for following composing character. */
4225 && UTF_COMPOSINGLIKE(reginput
, reginput
+ len
))
4227 /* raaron: This code makes a composing character get
4228 * ignored, which is the correct behavior (sometimes)
4229 * for voweled Hebrew texts. */
4231 status
= RA_NOMATCH
;
4243 status
= RA_NOMATCH
;
4244 else if ((cstrchr(OPERAND(scan
), c
) == NULL
) == (op
== ANYOF
))
4245 status
= RA_NOMATCH
;
4256 int opndc
= 0, inpc
;
4258 opnd
= OPERAND(scan
);
4259 /* Safety check (just in case 'encoding' was changed since
4260 * compiling the program). */
4261 if ((len
= (*mb_ptr2len
)(opnd
)) < 2)
4263 status
= RA_NOMATCH
;
4267 opndc
= mb_ptr2char(opnd
);
4268 if (enc_utf8
&& utf_iscomposing(opndc
))
4270 /* When only a composing char is given match at any
4271 * position where that composing char appears. */
4272 status
= RA_NOMATCH
;
4273 for (i
= 0; reginput
[i
] != NUL
; i
+= utf_char2len(inpc
))
4275 inpc
= mb_ptr2char(reginput
+ i
);
4276 if (!utf_iscomposing(inpc
))
4281 else if (opndc
== inpc
)
4283 /* Include all following composing chars. */
4284 len
= i
+ mb_ptr2len(reginput
+ i
);
4291 for (i
= 0; i
< len
; ++i
)
4292 if (opnd
[i
] != reginput
[i
])
4294 status
= RA_NOMATCH
;
4300 status
= RA_NOMATCH
;
4313 * When we run into BACK we need to check if we don't keep
4314 * looping without matching any input. The second and later
4315 * times a BACK is encountered it fails if the input is still
4316 * at the same position as the previous time.
4317 * The positions are stored in "backpos" and found by the
4318 * current value of "scan", the position in the RE program.
4320 bp
= (backpos_T
*)backpos
.ga_data
;
4321 for (i
= 0; i
< backpos
.ga_len
; ++i
)
4322 if (bp
[i
].bp_scan
== scan
)
4324 if (i
== backpos
.ga_len
)
4326 /* First time at this BACK, make room to store the pos. */
4327 if (ga_grow(&backpos
, 1) == FAIL
)
4331 /* get "ga_data" again, it may have changed */
4332 bp
= (backpos_T
*)backpos
.ga_data
;
4333 bp
[i
].bp_scan
= scan
;
4337 else if (reg_save_equal(&bp
[i
].bp_pos
))
4338 /* Still at same position as last time, fail. */
4339 status
= RA_NOMATCH
;
4341 if (status
!= RA_FAIL
&& status
!= RA_NOMATCH
)
4342 reg_save(&bp
[i
].bp_pos
, &backpos
);
4346 case MOPEN
+ 0: /* Match start: \zs */
4347 case MOPEN
+ 1: /* \( */
4359 rp
= regstack_push(RS_MOPEN
, scan
);
4365 save_se(&rp
->rs_un
.sesave
, ®_startpos
[no
],
4367 /* We simply continue and handle the result when done. */
4372 case NOPEN
: /* \%( */
4373 case NCLOSE
: /* \) after \%( */
4374 if (regstack_push(RS_NOPEN
, scan
) == NULL
)
4376 /* We simply continue and handle the result when done. */
4392 rp
= regstack_push(RS_ZOPEN
, scan
);
4398 save_se(&rp
->rs_un
.sesave
, ®_startzpos
[no
],
4400 /* We simply continue and handle the result when done. */
4406 case MCLOSE
+ 0: /* Match end: \ze */
4407 case MCLOSE
+ 1: /* \) */
4419 rp
= regstack_push(RS_MCLOSE
, scan
);
4425 save_se(&rp
->rs_un
.sesave
, ®_endpos
[no
], ®_endp
[no
]);
4426 /* We simply continue and handle the result when done. */
4432 case ZCLOSE
+ 1: /* \) after \z( */
4444 rp
= regstack_push(RS_ZCLOSE
, scan
);
4450 save_se(&rp
->rs_un
.sesave
, ®_endzpos
[no
],
4452 /* We simply continue and handle the result when done. */
4475 if (!REG_MULTI
) /* Single-line regexp */
4477 if (reg_endp
[no
] == NULL
)
4479 /* Backref was not set: Match an empty string. */
4484 /* Compare current input with back-ref in the same
4486 len
= (int)(reg_endp
[no
] - reg_startp
[no
]);
4487 if (cstrncmp(reg_startp
[no
], reginput
, &len
) != 0)
4488 status
= RA_NOMATCH
;
4491 else /* Multi-line regexp */
4493 if (reg_endpos
[no
].lnum
< 0)
4495 /* Backref was not set: Match an empty string. */
4500 if (reg_startpos
[no
].lnum
== reglnum
4501 && reg_endpos
[no
].lnum
== reglnum
)
4503 /* Compare back-ref within the current line. */
4504 len
= reg_endpos
[no
].col
- reg_startpos
[no
].col
;
4505 if (cstrncmp(regline
+ reg_startpos
[no
].col
,
4506 reginput
, &len
) != 0)
4507 status
= RA_NOMATCH
;
4511 /* Messy situation: Need to compare between two
4513 ccol
= reg_startpos
[no
].col
;
4514 clnum
= reg_startpos
[no
].lnum
;
4517 /* Since getting one line may invalidate
4518 * the other, need to make copy. Slow! */
4519 if (regline
!= reg_tofree
)
4521 len
= (int)STRLEN(regline
);
4522 if (reg_tofree
== NULL
4523 || len
>= (int)reg_tofreelen
)
4525 len
+= 50; /* get some extra */
4526 vim_free(reg_tofree
);
4527 reg_tofree
= alloc(len
);
4528 if (reg_tofree
== NULL
)
4530 status
= RA_FAIL
; /* outof memory!*/
4533 reg_tofreelen
= len
;
4535 STRCPY(reg_tofree
, regline
);
4536 reginput
= reg_tofree
4537 + (reginput
- regline
);
4538 regline
= reg_tofree
;
4541 /* Get the line to compare with. */
4542 p
= reg_getline(clnum
);
4543 if (clnum
== reg_endpos
[no
].lnum
)
4544 len
= reg_endpos
[no
].col
- ccol
;
4546 len
= (int)STRLEN(p
+ ccol
);
4548 if (cstrncmp(p
+ ccol
, reginput
, &len
) != 0)
4550 status
= RA_NOMATCH
; /* doesn't match */
4553 if (clnum
== reg_endpos
[no
].lnum
)
4554 break; /* match and at end! */
4555 if (reglnum
>= reg_maxline
)
4557 status
= RA_NOMATCH
; /* text too short */
4561 /* Advance to next line. */
4572 /* found a match! Note that regline may now point
4573 * to a copy of the line, that should not matter. */
4578 /* Matched the backref, skip over it. */
4598 if (re_extmatch_in
!= NULL
4599 && re_extmatch_in
->matches
[no
] != NULL
)
4601 len
= (int)STRLEN(re_extmatch_in
->matches
[no
]);
4602 if (cstrncmp(re_extmatch_in
->matches
[no
],
4603 reginput
, &len
) != 0)
4604 status
= RA_NOMATCH
;
4610 /* Backref was not set: Match an empty string. */
4618 if (OP(next
) != BRANCH
) /* No choice. */
4619 next
= OPERAND(scan
); /* Avoid recursion. */
4622 rp
= regstack_push(RS_BRANCH
, scan
);
4626 status
= RA_BREAK
; /* rest is below */
4633 if (OP(next
) == BRACE_SIMPLE
)
4635 bl_minval
= OPERAND_MIN(scan
);
4636 bl_maxval
= OPERAND_MAX(scan
);
4638 else if (OP(next
) >= BRACE_COMPLEX
4639 && OP(next
) < BRACE_COMPLEX
+ 10)
4641 no
= OP(next
) - BRACE_COMPLEX
;
4642 brace_min
[no
] = OPERAND_MIN(scan
);
4643 brace_max
[no
] = OPERAND_MAX(scan
);
4644 brace_count
[no
] = 0;
4648 EMSG(_(e_internal
)); /* Shouldn't happen */
4654 case BRACE_COMPLEX
+ 0:
4655 case BRACE_COMPLEX
+ 1:
4656 case BRACE_COMPLEX
+ 2:
4657 case BRACE_COMPLEX
+ 3:
4658 case BRACE_COMPLEX
+ 4:
4659 case BRACE_COMPLEX
+ 5:
4660 case BRACE_COMPLEX
+ 6:
4661 case BRACE_COMPLEX
+ 7:
4662 case BRACE_COMPLEX
+ 8:
4663 case BRACE_COMPLEX
+ 9:
4665 no
= op
- BRACE_COMPLEX
;
4668 /* If not matched enough times yet, try one more */
4669 if (brace_count
[no
] <= (brace_min
[no
] <= brace_max
[no
]
4670 ? brace_min
[no
] : brace_max
[no
]))
4672 rp
= regstack_push(RS_BRCPLX_MORE
, scan
);
4678 reg_save(&rp
->rs_un
.regsave
, &backpos
);
4679 next
= OPERAND(scan
);
4680 /* We continue and handle the result when done. */
4685 /* If matched enough times, may try matching some more */
4686 if (brace_min
[no
] <= brace_max
[no
])
4688 /* Range is the normal way around, use longest match */
4689 if (brace_count
[no
] <= brace_max
[no
])
4691 rp
= regstack_push(RS_BRCPLX_LONG
, scan
);
4697 reg_save(&rp
->rs_un
.regsave
, &backpos
);
4698 next
= OPERAND(scan
);
4699 /* We continue and handle the result when done. */
4705 /* Range is backwards, use shortest match first */
4706 if (brace_count
[no
] <= brace_min
[no
])
4708 rp
= regstack_push(RS_BRCPLX_SHORT
, scan
);
4713 reg_save(&rp
->rs_un
.regsave
, &backpos
);
4714 /* We continue and handle the result when done. */
4728 * Lookahead to avoid useless match attempts when we know
4729 * what character comes next.
4731 if (OP(next
) == EXACTLY
)
4733 rst
.nextb
= *OPERAND(next
);
4736 if (isupper(rst
.nextb
))
4737 rst
.nextb_ic
= TOLOWER_LOC(rst
.nextb
);
4739 rst
.nextb_ic
= TOUPPER_LOC(rst
.nextb
);
4742 rst
.nextb_ic
= rst
.nextb
;
4749 if (op
!= BRACE_SIMPLE
)
4751 rst
.minval
= (op
== STAR
) ? 0 : 1;
4752 rst
.maxval
= MAX_LIMIT
;
4756 rst
.minval
= bl_minval
;
4757 rst
.maxval
= bl_maxval
;
4761 * When maxval > minval, try matching as much as possible, up
4762 * to maxval. When maxval < minval, try matching at least the
4763 * minimal number (since the range is backwards, that's also
4766 rst
.count
= regrepeat(OPERAND(scan
), rst
.maxval
);
4772 if (rst
.minval
<= rst
.maxval
4773 ? rst
.count
>= rst
.minval
: rst
.count
>= rst
.maxval
)
4775 /* It could match. Prepare for trying to match what
4776 * follows. The code is below. Parameters are stored in
4777 * a regstar_T on the regstack. */
4778 if ((long)((unsigned)regstack
.ga_len
>> 10) >= p_mmp
)
4780 EMSG(_(e_maxmempat
));
4783 else if (ga_grow(®stack
, sizeof(regstar_T
)) == FAIL
)
4787 regstack
.ga_len
+= sizeof(regstar_T
);
4788 rp
= regstack_push(rst
.minval
<= rst
.maxval
4789 ? RS_STAR_LONG
: RS_STAR_SHORT
, scan
);
4794 *(((regstar_T
*)rp
) - 1) = rst
;
4795 status
= RA_BREAK
; /* skip the restore bits */
4800 status
= RA_NOMATCH
;
4808 rp
= regstack_push(RS_NOMATCH
, scan
);
4814 reg_save(&rp
->rs_un
.regsave
, &backpos
);
4815 next
= OPERAND(scan
);
4816 /* We continue and handle the result when done. */
4822 /* Need a bit of room to store extra positions. */
4823 if ((long)((unsigned)regstack
.ga_len
>> 10) >= p_mmp
)
4825 EMSG(_(e_maxmempat
));
4828 else if (ga_grow(®stack
, sizeof(regbehind_T
)) == FAIL
)
4832 regstack
.ga_len
+= sizeof(regbehind_T
);
4833 rp
= regstack_push(RS_BEHIND1
, scan
);
4839 reg_save(&rp
->rs_un
.regsave
, &backpos
);
4840 /* First try if what follows matches. If it does then we
4841 * check the behind match by looping. */
4849 if (behind_pos
.rs_u
.pos
.col
!= (colnr_T
)(reginput
- regline
)
4850 || behind_pos
.rs_u
.pos
.lnum
!= reglnum
)
4851 status
= RA_NOMATCH
;
4853 else if (behind_pos
.rs_u
.ptr
!= reginput
)
4854 status
= RA_NOMATCH
;
4858 if ((c
!= NUL
|| !REG_MULTI
|| reglnum
> reg_maxline
4859 || reg_line_lbr
) && (c
!= '\n' || !reg_line_lbr
))
4860 status
= RA_NOMATCH
;
4861 else if (reg_line_lbr
)
4868 status
= RA_MATCH
; /* Success! */
4874 printf("Illegal op code %d\n", op
);
4881 /* If we can't continue sequentially, break the inner loop. */
4882 if (status
!= RA_CONT
)
4885 /* Continue in inner loop, advance to next item. */
4888 } /* end of inner loop */
4891 * If there is something on the regstack execute the code for the state.
4892 * If the state is popped then loop and use the older state.
4894 while (regstack
.ga_len
> 0 && status
!= RA_FAIL
)
4896 rp
= (regitem_T
*)((char *)regstack
.ga_data
+ regstack
.ga_len
) - 1;
4897 switch (rp
->rs_state
)
4900 /* Result is passed on as-is, simply pop the state. */
4901 regstack_pop(&scan
);
4905 /* Pop the state. Restore pointers when there is no match. */
4906 if (status
== RA_NOMATCH
)
4907 restore_se(&rp
->rs_un
.sesave
, ®_startpos
[rp
->rs_no
],
4908 ®_startp
[rp
->rs_no
]);
4909 regstack_pop(&scan
);
4914 /* Pop the state. Restore pointers when there is no match. */
4915 if (status
== RA_NOMATCH
)
4916 restore_se(&rp
->rs_un
.sesave
, ®_startzpos
[rp
->rs_no
],
4917 ®_startzp
[rp
->rs_no
]);
4918 regstack_pop(&scan
);
4923 /* Pop the state. Restore pointers when there is no match. */
4924 if (status
== RA_NOMATCH
)
4925 restore_se(&rp
->rs_un
.sesave
, ®_endpos
[rp
->rs_no
],
4926 ®_endp
[rp
->rs_no
]);
4927 regstack_pop(&scan
);
4932 /* Pop the state. Restore pointers when there is no match. */
4933 if (status
== RA_NOMATCH
)
4934 restore_se(&rp
->rs_un
.sesave
, ®_endzpos
[rp
->rs_no
],
4935 ®_endzp
[rp
->rs_no
]);
4936 regstack_pop(&scan
);
4941 if (status
== RA_MATCH
)
4942 /* this branch matched, use it */
4943 regstack_pop(&scan
);
4946 if (status
!= RA_BREAK
)
4948 /* After a non-matching branch: try next one. */
4949 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
4952 if (scan
== NULL
|| OP(scan
) != BRANCH
)
4954 /* no more branches, didn't find a match */
4955 status
= RA_NOMATCH
;
4956 regstack_pop(&scan
);
4960 /* Prepare to try a branch. */
4961 rp
->rs_scan
= regnext(scan
);
4962 reg_save(&rp
->rs_un
.regsave
, &backpos
);
4963 scan
= OPERAND(scan
);
4968 case RS_BRCPLX_MORE
:
4969 /* Pop the state. Restore pointers when there is no match. */
4970 if (status
== RA_NOMATCH
)
4972 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
4973 --brace_count
[rp
->rs_no
]; /* decrement match count */
4975 regstack_pop(&scan
);
4978 case RS_BRCPLX_LONG
:
4979 /* Pop the state. Restore pointers when there is no match. */
4980 if (status
== RA_NOMATCH
)
4982 /* There was no match, but we did find enough matches. */
4983 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
4984 --brace_count
[rp
->rs_no
];
4985 /* continue with the items after "\{}" */
4988 regstack_pop(&scan
);
4989 if (status
== RA_CONT
)
4990 scan
= regnext(scan
);
4993 case RS_BRCPLX_SHORT
:
4994 /* Pop the state. Restore pointers when there is no match. */
4995 if (status
== RA_NOMATCH
)
4996 /* There was no match, try to match one more item. */
4997 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
4998 regstack_pop(&scan
);
4999 if (status
== RA_NOMATCH
)
5001 scan
= OPERAND(scan
);
5007 /* Pop the state. If the operand matches for NOMATCH or
5008 * doesn't match for MATCH/SUBPAT, we fail. Otherwise backup,
5009 * except for SUBPAT, and continue with the next item. */
5010 if (status
== (rp
->rs_no
== NOMATCH
? RA_MATCH
: RA_NOMATCH
))
5011 status
= RA_NOMATCH
;
5015 if (rp
->rs_no
!= SUBPAT
) /* zero-width */
5016 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
5018 regstack_pop(&scan
);
5019 if (status
== RA_CONT
)
5020 scan
= regnext(scan
);
5024 if (status
== RA_NOMATCH
)
5026 regstack_pop(&scan
);
5027 regstack
.ga_len
-= sizeof(regbehind_T
);
5031 /* The stuff after BEHIND/NOBEHIND matches. Now try if
5032 * the behind part does (not) match before the current
5033 * position in the input. This must be done at every
5034 * position in the input and checking if the match ends at
5035 * the current position. */
5037 /* save the position after the found match for next */
5038 reg_save(&(((regbehind_T
*)rp
) - 1)->save_after
, &backpos
);
5040 /* start looking for a match with operand at the current
5041 * postion. Go back one character until we find the
5042 * result, hitting the start of the line or the previous
5043 * line (for multi-line matching).
5044 * Set behind_pos to where the match should end, BHPOS
5045 * will match it. Save the current value. */
5046 (((regbehind_T
*)rp
) - 1)->save_behind
= behind_pos
;
5047 behind_pos
= rp
->rs_un
.regsave
;
5049 rp
->rs_state
= RS_BEHIND2
;
5051 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
5052 scan
= OPERAND(rp
->rs_scan
);
5058 * Looping for BEHIND / NOBEHIND match.
5060 if (status
== RA_MATCH
&& reg_save_equal(&behind_pos
))
5062 /* found a match that ends where "next" started */
5063 behind_pos
= (((regbehind_T
*)rp
) - 1)->save_behind
;
5064 if (rp
->rs_no
== BEHIND
)
5065 reg_restore(&(((regbehind_T
*)rp
) - 1)->save_after
,
5068 /* But we didn't want a match. */
5069 status
= RA_NOMATCH
;
5070 regstack_pop(&scan
);
5071 regstack
.ga_len
-= sizeof(regbehind_T
);
5075 /* No match: Go back one character. May go to previous
5080 if (rp
->rs_un
.regsave
.rs_u
.pos
.col
== 0)
5082 if (rp
->rs_un
.regsave
.rs_u
.pos
.lnum
5083 < behind_pos
.rs_u
.pos
.lnum
5085 --rp
->rs_un
.regsave
.rs_u
.pos
.lnum
)
5090 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
5091 rp
->rs_un
.regsave
.rs_u
.pos
.col
=
5092 (colnr_T
)STRLEN(regline
);
5096 --rp
->rs_un
.regsave
.rs_u
.pos
.col
;
5100 if (rp
->rs_un
.regsave
.rs_u
.ptr
== regline
)
5103 --rp
->rs_un
.regsave
.rs_u
.ptr
;
5107 /* Advanced, prepare for finding match again. */
5108 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
5109 scan
= OPERAND(rp
->rs_scan
);
5113 /* Can't advance. For NOBEHIND that's a match. */
5114 behind_pos
= (((regbehind_T
*)rp
) - 1)->save_behind
;
5115 if (rp
->rs_no
== NOBEHIND
)
5117 reg_restore(&(((regbehind_T
*)rp
) - 1)->save_after
,
5122 status
= RA_NOMATCH
;
5123 regstack_pop(&scan
);
5124 regstack
.ga_len
-= sizeof(regbehind_T
);
5132 regstar_T
*rst
= ((regstar_T
*)rp
) - 1;
5134 if (status
== RA_MATCH
)
5136 regstack_pop(&scan
);
5137 regstack
.ga_len
-= sizeof(regstar_T
);
5141 /* Tried once already, restore input pointers. */
5142 if (status
!= RA_BREAK
)
5143 reg_restore(&rp
->rs_un
.regsave
, &backpos
);
5145 /* Repeat until we found a position where it could match. */
5148 if (status
!= RA_BREAK
)
5150 /* Tried first position already, advance. */
5151 if (rp
->rs_state
== RS_STAR_LONG
)
5153 /* Trying for longest match, but couldn't or
5154 * didn't match -- back up one char. */
5155 if (--rst
->count
< rst
->minval
)
5157 if (reginput
== regline
)
5159 /* backup to last char of previous line */
5161 regline
= reg_getline(reglnum
);
5162 /* Just in case regrepeat() didn't count
5164 if (regline
== NULL
)
5166 reginput
= regline
+ STRLEN(regline
);
5170 mb_ptr_back(regline
, reginput
);
5174 /* Range is backwards, use shortest match first.
5175 * Careful: maxval and minval are exchanged!
5176 * Couldn't or didn't match: try advancing one
5178 if (rst
->count
== rst
->minval
5179 || regrepeat(OPERAND(rp
->rs_scan
), 1L) == 0)
5187 status
= RA_NOMATCH
;
5189 /* If it could match, try it. */
5190 if (rst
->nextb
== NUL
|| *reginput
== rst
->nextb
5191 || *reginput
== rst
->nextb_ic
)
5193 reg_save(&rp
->rs_un
.regsave
, &backpos
);
5194 scan
= regnext(rp
->rs_scan
);
5199 if (status
!= RA_CONT
)
5202 regstack_pop(&scan
);
5203 regstack
.ga_len
-= sizeof(regstar_T
);
5204 status
= RA_NOMATCH
;
5210 /* If we want to continue the inner loop or didn't pop a state
5211 * continue matching loop */
5212 if (status
== RA_CONT
|| rp
== (regitem_T
*)
5213 ((char *)regstack
.ga_data
+ regstack
.ga_len
) - 1)
5217 /* May need to continue with the inner loop, starting at "scan". */
5218 if (status
== RA_CONT
)
5222 * If the regstack is empty or something failed we are done.
5224 if (regstack
.ga_len
== 0 || status
== RA_FAIL
)
5229 * We get here only if there's trouble -- normally "case END" is
5230 * the terminating point.
5234 printf("Premature EOL\n");
5237 if (status
== RA_FAIL
)
5239 return (status
== RA_MATCH
);
5242 } /* End of loop until the regstack is empty. */
5248 * Push an item onto the regstack.
5249 * Returns pointer to new item. Returns NULL when out of memory.
5252 regstack_push(state
, scan
)
5258 if ((long)((unsigned)regstack
.ga_len
>> 10) >= p_mmp
)
5260 EMSG(_(e_maxmempat
));
5263 if (ga_grow(®stack
, sizeof(regitem_T
)) == FAIL
)
5266 rp
= (regitem_T
*)((char *)regstack
.ga_data
+ regstack
.ga_len
);
5267 rp
->rs_state
= state
;
5270 regstack
.ga_len
+= sizeof(regitem_T
);
5275 * Pop an item from the regstack.
5283 rp
= (regitem_T
*)((char *)regstack
.ga_data
+ regstack
.ga_len
) - 1;
5284 *scan
= rp
->rs_scan
;
5286 regstack
.ga_len
-= sizeof(regitem_T
);
5290 * regrepeat - repeatedly match something simple, return how many.
5291 * Advances reginput (and reglnum) to just after the matched chars.
5294 regrepeat(p
, maxcount
)
5296 long maxcount
; /* maximum number of matches allowed */
5304 scan
= reginput
; /* Make local copy of reginput for speed. */
5310 while (count
< maxcount
)
5312 /* Matching anything means we continue until end-of-line (or
5313 * end-of-file for ANY + ADD_NL), only limited by maxcount. */
5314 while (*scan
!= NUL
&& count
< maxcount
)
5319 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5320 || reg_line_lbr
|| count
== maxcount
)
5322 ++count
; /* count the line-break */
5331 case IDENT
+ ADD_NL
:
5335 case SIDENT
+ ADD_NL
:
5336 while (count
< maxcount
)
5338 if (vim_isIDc(*scan
) && (testval
|| !VIM_ISDIGIT(*scan
)))
5342 else if (*scan
== NUL
)
5344 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5352 else if (reg_line_lbr
&& *scan
== '\n' && WITH_NL(OP(p
)))
5361 case KWORD
+ ADD_NL
:
5365 case SKWORD
+ ADD_NL
:
5366 while (count
< maxcount
)
5368 if (vim_iswordp(scan
) && (testval
|| !VIM_ISDIGIT(*scan
)))
5372 else if (*scan
== NUL
)
5374 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5382 else if (reg_line_lbr
&& *scan
== '\n' && WITH_NL(OP(p
)))
5391 case FNAME
+ ADD_NL
:
5395 case SFNAME
+ ADD_NL
:
5396 while (count
< maxcount
)
5398 if (vim_isfilec(*scan
) && (testval
|| !VIM_ISDIGIT(*scan
)))
5402 else if (*scan
== NUL
)
5404 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5412 else if (reg_line_lbr
&& *scan
== '\n' && WITH_NL(OP(p
)))
5421 case PRINT
+ ADD_NL
:
5425 case SPRINT
+ ADD_NL
:
5426 while (count
< maxcount
)
5430 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5438 else if (ptr2cells(scan
) == 1 && (testval
|| !VIM_ISDIGIT(*scan
)))
5442 else if (reg_line_lbr
&& *scan
== '\n' && WITH_NL(OP(p
)))
5451 case WHITE
+ ADD_NL
:
5452 testval
= mask
= RI_WHITE
;
5454 while (count
< maxcount
)
5461 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5470 else if (has_mbyte
&& (l
= (*mb_ptr2len
)(scan
)) > 1)
5477 else if ((class_tab
[*scan
] & mask
) == testval
)
5479 else if (reg_line_lbr
&& *scan
== '\n' && WITH_NL(OP(p
)))
5488 case NWHITE
+ ADD_NL
:
5492 case DIGIT
+ ADD_NL
:
5493 testval
= mask
= RI_DIGIT
;
5496 case NDIGIT
+ ADD_NL
:
5501 testval
= mask
= RI_HEX
;
5508 case OCTAL
+ ADD_NL
:
5509 testval
= mask
= RI_OCTAL
;
5512 case NOCTAL
+ ADD_NL
:
5517 testval
= mask
= RI_WORD
;
5520 case NWORD
+ ADD_NL
:
5525 testval
= mask
= RI_HEAD
;
5528 case NHEAD
+ ADD_NL
:
5532 case ALPHA
+ ADD_NL
:
5533 testval
= mask
= RI_ALPHA
;
5536 case NALPHA
+ ADD_NL
:
5540 case LOWER
+ ADD_NL
:
5541 testval
= mask
= RI_LOWER
;
5544 case NLOWER
+ ADD_NL
:
5548 case UPPER
+ ADD_NL
:
5549 testval
= mask
= RI_UPPER
;
5552 case NUPPER
+ ADD_NL
:
5560 /* This doesn't do a multi-byte character, because a MULTIBYTECODE
5561 * would have been used for it. */
5564 cu
= TOUPPER_LOC(*opnd
);
5565 cl
= TOLOWER_LOC(*opnd
);
5566 while (count
< maxcount
&& (*scan
== cu
|| *scan
== cl
))
5575 while (count
< maxcount
&& *scan
== cu
)
5589 /* Safety check (just in case 'encoding' was changed since
5590 * compiling the program). */
5591 if ((len
= (*mb_ptr2len
)(opnd
)) > 1)
5593 if (ireg_ic
&& enc_utf8
)
5594 cf
= utf_fold(utf_ptr2char(opnd
));
5595 while (count
< maxcount
)
5597 for (i
= 0; i
< len
; ++i
)
5598 if (opnd
[i
] != scan
[i
])
5600 if (i
< len
&& (!ireg_ic
|| !enc_utf8
5601 || utf_fold(utf_ptr2char(scan
)) != cf
))
5612 case ANYOF
+ ADD_NL
:
5617 case ANYBUT
+ ADD_NL
:
5618 while (count
< maxcount
)
5625 if (!REG_MULTI
|| !WITH_NL(OP(p
)) || reglnum
> reg_maxline
5633 else if (reg_line_lbr
&& *scan
== '\n' && WITH_NL(OP(p
)))
5636 else if (has_mbyte
&& (len
= (*mb_ptr2len
)(scan
)) > 1)
5638 if ((cstrchr(opnd
, (*mb_ptr2char
)(scan
)) == NULL
) == testval
)
5645 if ((cstrchr(opnd
, *scan
) == NULL
) == testval
)
5654 while (count
< maxcount
5655 && ((*scan
== NUL
&& reglnum
<= reg_maxline
&& !reg_line_lbr
5656 && REG_MULTI
) || (*scan
== '\n' && reg_line_lbr
)))
5669 default: /* Oh dear. Called inappropriately. */
5672 printf("Called regrepeat with op code %d\n", OP(p
));
5683 * regnext - dig the "next" pointer out of a node
5691 if (p
== JUST_CALC_SIZE
)
5705 * Check the regexp program for its magic number.
5706 * Return TRUE if it's wrong.
5711 if (UCHARAT(REG_MULTI
5712 ? reg_mmatch
->regprog
->program
5713 : reg_match
->regprog
->program
) != REGMAGIC
)
5722 * Cleanup the subexpressions, if this wasn't done yet.
5723 * This construction is used to clear the subexpressions only when they are
5724 * used (to increase speed).
5729 if (need_clear_subexpr
)
5733 /* Use 0xff to set lnum to -1 */
5734 vim_memset(reg_startpos
, 0xff, sizeof(lpos_T
) * NSUBEXP
);
5735 vim_memset(reg_endpos
, 0xff, sizeof(lpos_T
) * NSUBEXP
);
5739 vim_memset(reg_startp
, 0, sizeof(char_u
*) * NSUBEXP
);
5740 vim_memset(reg_endp
, 0, sizeof(char_u
*) * NSUBEXP
);
5742 need_clear_subexpr
= FALSE
;
5750 if (need_clear_zsubexpr
)
5754 /* Use 0xff to set lnum to -1 */
5755 vim_memset(reg_startzpos
, 0xff, sizeof(lpos_T
) * NSUBEXP
);
5756 vim_memset(reg_endzpos
, 0xff, sizeof(lpos_T
) * NSUBEXP
);
5760 vim_memset(reg_startzp
, 0, sizeof(char_u
*) * NSUBEXP
);
5761 vim_memset(reg_endzp
, 0, sizeof(char_u
*) * NSUBEXP
);
5763 need_clear_zsubexpr
= FALSE
;
5769 * Advance reglnum, regline and reginput to the next line.
5774 regline
= reg_getline(++reglnum
);
5780 * Save the input line and position in a regsave_T.
5789 save
->rs_u
.pos
.col
= (colnr_T
)(reginput
- regline
);
5790 save
->rs_u
.pos
.lnum
= reglnum
;
5793 save
->rs_u
.ptr
= reginput
;
5794 save
->rs_len
= gap
->ga_len
;
5798 * Restore the input line and position from a regsave_T.
5801 reg_restore(save
, gap
)
5807 if (reglnum
!= save
->rs_u
.pos
.lnum
)
5809 /* only call reg_getline() when the line number changed to save
5811 reglnum
= save
->rs_u
.pos
.lnum
;
5812 regline
= reg_getline(reglnum
);
5814 reginput
= regline
+ save
->rs_u
.pos
.col
;
5817 reginput
= save
->rs_u
.ptr
;
5818 gap
->ga_len
= save
->rs_len
;
5822 * Return TRUE if current position is equal to saved position.
5825 reg_save_equal(save
)
5829 return reglnum
== save
->rs_u
.pos
.lnum
5830 && reginput
== regline
+ save
->rs_u
.pos
.col
;
5831 return reginput
== save
->rs_u
.ptr
;
5835 * Tentatively set the sub-expression start to the current position (after
5836 * calling regmatch() they will have changed). Need to save the existing
5837 * values for when there is no match.
5838 * Use se_save() to use pointer (save_se_multi()) or position (save_se_one()),
5839 * depending on REG_MULTI.
5842 save_se_multi(savep
, posp
)
5846 savep
->se_u
.pos
= *posp
;
5847 posp
->lnum
= reglnum
;
5848 posp
->col
= (colnr_T
)(reginput
- regline
);
5852 save_se_one(savep
, pp
)
5856 savep
->se_u
.ptr
= *pp
;
5861 * Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
5864 re_num_cmp(val
, scan
)
5868 long_u n
= OPERAND_MIN(scan
);
5870 if (OPERAND_CMP(scan
) == '>')
5872 if (OPERAND_CMP(scan
) == '<')
5881 * regdump - dump a regexp onto stdout in vaguely comprehensible form
5889 int op
= EXACTLY
; /* Arbitrary non-END op. */
5893 printf("\r\nregcomp(%s):\r\n", pattern
);
5897 * Loop until we find the END that isn't before a referred next (an END
5898 * can also appear in a NOMATCH operand).
5900 while (op
!= END
|| s
<= end
)
5903 printf("%2d%s", (int)(s
- r
->program
), regprop(s
)); /* Where, what. */
5905 if (next
== NULL
) /* Next ptr. */
5908 printf("(%d)", (int)((s
- r
->program
) + (next
- s
)));
5911 if (op
== BRACE_LIMITS
)
5913 /* Two short ints */
5914 printf(" minval %ld, maxval %ld", OPERAND_MIN(s
), OPERAND_MAX(s
));
5918 if (op
== ANYOF
|| op
== ANYOF
+ ADD_NL
5919 || op
== ANYBUT
|| op
== ANYBUT
+ ADD_NL
5922 /* Literal string, where present. */
5930 /* Header fields of interest. */
5931 if (r
->regstart
!= NUL
)
5932 printf("start `%s' 0x%x; ", r
->regstart
< 256
5933 ? (char *)transchar(r
->regstart
)
5934 : "multibyte", r
->regstart
);
5936 printf("anchored; ");
5937 if (r
->regmust
!= NULL
)
5938 printf("must have \"%s\"", r
->regmust
);
5943 * regprop - printable representation of opcode
5950 static char_u buf
[50];
5952 (void) strcpy(buf
, ":");
6001 case ANYOF
+ ADD_NL
:
6007 case ANYBUT
+ ADD_NL
:
6013 case IDENT
+ ADD_NL
:
6019 case SIDENT
+ ADD_NL
:
6025 case KWORD
+ ADD_NL
:
6031 case SKWORD
+ ADD_NL
:
6037 case FNAME
+ ADD_NL
:
6043 case SFNAME
+ ADD_NL
:
6049 case PRINT
+ ADD_NL
:
6055 case SPRINT
+ ADD_NL
:
6061 case WHITE
+ ADD_NL
:
6067 case NWHITE
+ ADD_NL
:
6073 case DIGIT
+ ADD_NL
:
6079 case NDIGIT
+ ADD_NL
:
6097 case OCTAL
+ ADD_NL
:
6103 case NOCTAL
+ ADD_NL
:
6115 case NWORD
+ ADD_NL
:
6127 case NHEAD
+ ADD_NL
:
6133 case ALPHA
+ ADD_NL
:
6139 case NALPHA
+ ADD_NL
:
6145 case LOWER
+ ADD_NL
:
6151 case NLOWER
+ ADD_NL
:
6157 case UPPER
+ ADD_NL
:
6163 case NUPPER
+ ADD_NL
:
6193 sprintf(buf
+ STRLEN(buf
), "MOPEN%d", OP(op
) - MOPEN
);
6208 sprintf(buf
+ STRLEN(buf
), "MCLOSE%d", OP(op
) - MCLOSE
);
6220 sprintf(buf
+ STRLEN(buf
), "BACKREF%d", OP(op
) - BACKREF
);
6239 sprintf(buf
+ STRLEN(buf
), "ZOPEN%d", OP(op
) - ZOPEN
);
6251 sprintf(buf
+ STRLEN(buf
), "ZCLOSE%d", OP(op
) - ZCLOSE
);
6263 sprintf(buf
+ STRLEN(buf
), "ZREF%d", OP(op
) - ZREF
);
6294 case BRACE_COMPLEX
+ 0:
6295 case BRACE_COMPLEX
+ 1:
6296 case BRACE_COMPLEX
+ 2:
6297 case BRACE_COMPLEX
+ 3:
6298 case BRACE_COMPLEX
+ 4:
6299 case BRACE_COMPLEX
+ 5:
6300 case BRACE_COMPLEX
+ 6:
6301 case BRACE_COMPLEX
+ 7:
6302 case BRACE_COMPLEX
+ 8:
6303 case BRACE_COMPLEX
+ 9:
6304 sprintf(buf
+ STRLEN(buf
), "BRACE_COMPLEX%d", OP(op
) - BRACE_COMPLEX
);
6309 p
= "MULTIBYTECODE";
6316 sprintf(buf
+ STRLEN(buf
), "corrupt %d", OP(op
));
6321 (void) strcat(buf
, p
);
6327 static void mb_decompose
__ARGS((int c
, int *c1
, int *c2
, int *c3
));
6335 /* 0xfb20 - 0xfb4f */
6336 static decomp_T decomp_table
[0xfb4f-0xfb20+1] =
6338 {0x5e2,0,0}, /* 0xfb20 alt ayin */
6339 {0x5d0,0,0}, /* 0xfb21 alt alef */
6340 {0x5d3,0,0}, /* 0xfb22 alt dalet */
6341 {0x5d4,0,0}, /* 0xfb23 alt he */
6342 {0x5db,0,0}, /* 0xfb24 alt kaf */
6343 {0x5dc,0,0}, /* 0xfb25 alt lamed */
6344 {0x5dd,0,0}, /* 0xfb26 alt mem-sofit */
6345 {0x5e8,0,0}, /* 0xfb27 alt resh */
6346 {0x5ea,0,0}, /* 0xfb28 alt tav */
6347 {'+', 0, 0}, /* 0xfb29 alt plus */
6348 {0x5e9, 0x5c1, 0}, /* 0xfb2a shin+shin-dot */
6349 {0x5e9, 0x5c2, 0}, /* 0xfb2b shin+sin-dot */
6350 {0x5e9, 0x5c1, 0x5bc}, /* 0xfb2c shin+shin-dot+dagesh */
6351 {0x5e9, 0x5c2, 0x5bc}, /* 0xfb2d shin+sin-dot+dagesh */
6352 {0x5d0, 0x5b7, 0}, /* 0xfb2e alef+patah */
6353 {0x5d0, 0x5b8, 0}, /* 0xfb2f alef+qamats */
6354 {0x5d0, 0x5b4, 0}, /* 0xfb30 alef+hiriq */
6355 {0x5d1, 0x5bc, 0}, /* 0xfb31 bet+dagesh */
6356 {0x5d2, 0x5bc, 0}, /* 0xfb32 gimel+dagesh */
6357 {0x5d3, 0x5bc, 0}, /* 0xfb33 dalet+dagesh */
6358 {0x5d4, 0x5bc, 0}, /* 0xfb34 he+dagesh */
6359 {0x5d5, 0x5bc, 0}, /* 0xfb35 vav+dagesh */
6360 {0x5d6, 0x5bc, 0}, /* 0xfb36 zayin+dagesh */
6361 {0xfb37, 0, 0}, /* 0xfb37 -- UNUSED */
6362 {0x5d8, 0x5bc, 0}, /* 0xfb38 tet+dagesh */
6363 {0x5d9, 0x5bc, 0}, /* 0xfb39 yud+dagesh */
6364 {0x5da, 0x5bc, 0}, /* 0xfb3a kaf sofit+dagesh */
6365 {0x5db, 0x5bc, 0}, /* 0xfb3b kaf+dagesh */
6366 {0x5dc, 0x5bc, 0}, /* 0xfb3c lamed+dagesh */
6367 {0xfb3d, 0, 0}, /* 0xfb3d -- UNUSED */
6368 {0x5de, 0x5bc, 0}, /* 0xfb3e mem+dagesh */
6369 {0xfb3f, 0, 0}, /* 0xfb3f -- UNUSED */
6370 {0x5e0, 0x5bc, 0}, /* 0xfb40 nun+dagesh */
6371 {0x5e1, 0x5bc, 0}, /* 0xfb41 samech+dagesh */
6372 {0xfb42, 0, 0}, /* 0xfb42 -- UNUSED */
6373 {0x5e3, 0x5bc, 0}, /* 0xfb43 pe sofit+dagesh */
6374 {0x5e4, 0x5bc,0}, /* 0xfb44 pe+dagesh */
6375 {0xfb45, 0, 0}, /* 0xfb45 -- UNUSED */
6376 {0x5e6, 0x5bc, 0}, /* 0xfb46 tsadi+dagesh */
6377 {0x5e7, 0x5bc, 0}, /* 0xfb47 qof+dagesh */
6378 {0x5e8, 0x5bc, 0}, /* 0xfb48 resh+dagesh */
6379 {0x5e9, 0x5bc, 0}, /* 0xfb49 shin+dagesh */
6380 {0x5ea, 0x5bc, 0}, /* 0xfb4a tav+dagesh */
6381 {0x5d5, 0x5b9, 0}, /* 0xfb4b vav+holam */
6382 {0x5d1, 0x5bf, 0}, /* 0xfb4c bet+rafe */
6383 {0x5db, 0x5bf, 0}, /* 0xfb4d kaf+rafe */
6384 {0x5e4, 0x5bf, 0}, /* 0xfb4e pe+rafe */
6385 {0x5d0, 0x5dc, 0} /* 0xfb4f alef-lamed */
6389 mb_decompose(c
, c1
, c2
, c3
)
6390 int c
, *c1
, *c2
, *c3
;
6394 if (c
>= 0x4b20 && c
<= 0xfb4f)
6396 d
= decomp_table
[c
- 0xfb20];
6410 * Compare two strings, ignore case if ireg_ic set.
6411 * Return 0 if strings match, non-zero otherwise.
6412 * Correct the length "*n" when composing characters are ignored.
6422 result
= STRNCMP(s1
, s2
, *n
);
6424 result
= MB_STRNICMP(s1
, s2
, *n
);
6427 /* if it failed and it's utf8 and we want to combineignore: */
6428 if (result
!= 0 && enc_utf8
&& ireg_icombine
)
6430 char_u
*str1
, *str2
;
6431 int c1
, c2
, c11
, c12
;
6434 /* we have to handle the strcmp ourselves, since it is necessary to
6435 * deal with the composing characters by ignoring them: */
6439 while ((int)(str1
- s1
) < *n
)
6441 c1
= mb_ptr2char_adv(&str1
);
6442 c2
= mb_ptr2char_adv(&str2
);
6444 /* decompose the character if necessary, into 'base' characters
6445 * because I don't care about Arabic, I will hard-code the Hebrew
6446 * which I *do* care about! So sue me... */
6447 if (c1
!= c2
&& (!ireg_ic
|| utf_fold(c1
) != utf_fold(c2
)))
6449 /* decomposition necessary? */
6450 mb_decompose(c1
, &c11
, &junk
, &junk
);
6451 mb_decompose(c2
, &c12
, &junk
, &junk
);
6454 if (c11
!= c12
&& (!ireg_ic
|| utf_fold(c11
) != utf_fold(c12
)))
6460 *n
= (int)(str2
- s2
);
6468 * cstrchr: This function is used a lot for simple searches, keep it fast!
6480 || (!enc_utf8
&& mb_char2len(c
) > 1)
6483 return vim_strchr(s
, c
);
6485 /* tolower() and toupper() can be slow, comparing twice should be a lot
6486 * faster (esp. when using MS Visual C++!).
6487 * For UTF-8 need to use folded case. */
6489 if (enc_utf8
&& c
> 0x80)
6494 cc
= TOLOWER_LOC(c
);
6495 else if (islower(c
))
6496 cc
= TOUPPER_LOC(c
);
6498 return vim_strchr(s
, c
);
6503 for (p
= s
; *p
!= NUL
; p
+= (*mb_ptr2len
)(p
))
6505 if (enc_utf8
&& c
> 0x80)
6507 if (utf_fold(utf_ptr2char(p
)) == cc
)
6510 else if (*p
== c
|| *p
== cc
)
6516 /* Faster version for when there are no multi-byte characters. */
6517 for (p
= s
; *p
!= NUL
; ++p
)
6518 if (*p
== c
|| *p
== cc
)
6524 /***************************************************************
6526 ***************************************************************/
6528 /* This stuff below really confuses cc on an SGI -- webb */
6531 # define __ARGS(x) ()
6535 * We should define ftpr as a pointer to a function returning a pointer to
6536 * a function returning a pointer to a function ...
6537 * This is impossible, so we declare a pointer to a function returning a
6538 * pointer to a function returning void. This should work for all compilers.
6540 typedef void (*(*fptr_T
) __ARGS((int *, int)))();
6542 static fptr_T do_upper
__ARGS((int *, int));
6543 static fptr_T do_Upper
__ARGS((int *, int));
6544 static fptr_T do_lower
__ARGS((int *, int));
6545 static fptr_T do_Lower
__ARGS((int *, int));
6547 static int vim_regsub_both
__ARGS((char_u
*source
, char_u
*dest
, int copy
, int magic
, int backslash
));
6556 return (fptr_T
)NULL
;
6566 return (fptr_T
)do_Upper
;
6576 return (fptr_T
)NULL
;
6586 return (fptr_T
)do_Lower
;
6590 * regtilde(): Replace tildes in the pattern by the old pattern.
6592 * Short explanation of the tilde: It stands for the previous replacement
6593 * pattern. If that previous pattern also contains a ~ we should go back a
6594 * step further... But we insert the previous pattern into the current one
6595 * and remember that.
6596 * This still does not handle the case where "magic" changes. So require the
6597 * user to keep his hands off of "magic".
6599 * The tildes are parsed once before the first call to vim_regsub().
6602 regtilde(source
, magic
)
6606 char_u
*newsub
= source
;
6612 for (p
= newsub
; *p
; ++p
)
6614 if ((*p
== '~' && magic
) || (*p
== '\\' && *(p
+ 1) == '~' && !magic
))
6616 if (reg_prev_sub
!= NULL
)
6618 /* length = len(newsub) - 1 + len(prev_sub) + 1 */
6619 prevlen
= (int)STRLEN(reg_prev_sub
);
6620 tmpsub
= alloc((unsigned)(STRLEN(newsub
) + prevlen
));
6624 len
= (int)(p
- newsub
); /* not including ~ */
6625 mch_memmove(tmpsub
, newsub
, (size_t)len
);
6626 /* interpretate tilde */
6627 mch_memmove(tmpsub
+ len
, reg_prev_sub
, (size_t)prevlen
);
6630 ++p
; /* back off \ */
6631 STRCPY(tmpsub
+ len
+ prevlen
, p
+ 1);
6633 if (newsub
!= source
) /* already allocated newsub */
6636 p
= newsub
+ len
+ prevlen
;
6640 STRCPY(p
, p
+ 1); /* remove '~' */
6642 STRCPY(p
, p
+ 2); /* remove '\~' */
6647 if (*p
== '\\' && p
[1]) /* skip escaped characters */
6651 p
+= (*mb_ptr2len
)(p
) - 1;
6656 vim_free(reg_prev_sub
);
6657 if (newsub
!= source
) /* newsub was allocated, just keep it */
6658 reg_prev_sub
= newsub
;
6659 else /* no ~ found, need to save newsub */
6660 reg_prev_sub
= vim_strsave(newsub
);
6665 static int can_f_submatch
= FALSE
; /* TRUE when submatch() can be used */
6667 /* These pointers are used instead of reg_match and reg_mmatch for
6668 * reg_submatch(). Needed for when the substitution string is an expression
6669 * that contains a call to substitute() and submatch(). */
6670 static regmatch_T
*submatch_match
;
6671 static regmmatch_T
*submatch_mmatch
;
6674 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
6676 * vim_regsub() - perform substitutions after a vim_regexec() or
6677 * vim_regexec_multi() match.
6679 * If "copy" is TRUE really copy into "dest".
6680 * If "copy" is FALSE nothing is copied, this is just to find out the length
6683 * If "backslash" is TRUE, a backslash will be removed later, need to double
6684 * them to keep them, and insert a backslash before a CR to avoid it being
6685 * replaced with a line break later.
6687 * Note: The matched text must not change between the call of
6688 * vim_regexec()/vim_regexec_multi() and vim_regsub()! It would make the back
6689 * references invalid!
6691 * Returns the size of the replacement, including terminating NUL.
6694 vim_regsub(rmp
, source
, dest
, copy
, magic
, backslash
)
6705 return vim_regsub_both(source
, dest
, copy
, magic
, backslash
);
6710 vim_regsub_multi(rmp
, lnum
, source
, dest
, copy
, magic
, backslash
)
6721 reg_buf
= curbuf
; /* always works on the current buffer! */
6722 reg_firstlnum
= lnum
;
6723 reg_maxline
= curbuf
->b_ml
.ml_line_count
- lnum
;
6724 return vim_regsub_both(source
, dest
, copy
, magic
, backslash
);
6728 vim_regsub_both(source
, dest
, copy
, magic
, backslash
)
6741 fptr_T func
= (fptr_T
)NULL
;
6742 linenr_T clnum
= 0; /* init for GCC */
6743 int len
= 0; /* init for GCC */
6745 static char_u
*eval_result
= NULL
;
6748 /* Be paranoid... */
6749 if (source
== NULL
|| dest
== NULL
)
6754 if (prog_magic_wrong())
6760 * When the substitute part starts with "\=" evaluate it as an expression.
6762 if (source
[0] == '\\' && source
[1] == '='
6764 && !can_f_submatch
/* can't do this recursively */
6769 /* To make sure that the length doesn't change between checking the
6770 * length and copying the string, and to speed up things, the
6771 * resulting string is saved from the call with "copy" == FALSE to the
6772 * call with "copy" == TRUE. */
6775 if (eval_result
!= NULL
)
6777 STRCPY(dest
, eval_result
);
6778 dst
+= STRLEN(eval_result
);
6779 vim_free(eval_result
);
6785 linenr_T save_reg_maxline
;
6786 win_T
*save_reg_win
;
6789 vim_free(eval_result
);
6791 /* The expression may contain substitute(), which calls us
6792 * recursively. Make sure submatch() gets the text from the first
6793 * level. Don't need to save "reg_buf", because
6794 * vim_regexec_multi() can't be called recursively. */
6795 submatch_match
= reg_match
;
6796 submatch_mmatch
= reg_mmatch
;
6797 save_reg_maxline
= reg_maxline
;
6798 save_reg_win
= reg_win
;
6799 save_ireg_ic
= ireg_ic
;
6800 can_f_submatch
= TRUE
;
6802 eval_result
= eval_to_string(source
+ 2, NULL
, TRUE
);
6803 if (eval_result
!= NULL
)
6805 for (s
= eval_result
; *s
!= NUL
; mb_ptr_adv(s
))
6807 /* Change NL to CR, so that it becomes a line break.
6808 * Skip over a backslashed character. */
6811 else if (*s
== '\\' && s
[1] != NUL
)
6815 dst
+= STRLEN(eval_result
);
6818 reg_match
= submatch_match
;
6819 reg_mmatch
= submatch_mmatch
;
6820 reg_maxline
= save_reg_maxline
;
6821 reg_win
= save_reg_win
;
6822 ireg_ic
= save_ireg_ic
;
6823 can_f_submatch
= FALSE
;
6828 while ((c
= *src
++) != NUL
)
6830 if (c
== '&' && magic
)
6832 else if (c
== '\\' && *src
!= NUL
)
6834 if (*src
== '&' && !magic
)
6839 else if ('0' <= *src
&& *src
<= '9')
6843 else if (vim_strchr((char_u
*)"uUlLeE", *src
))
6847 case 'u': func
= (fptr_T
)do_upper
;
6849 case 'U': func
= (fptr_T
)do_Upper
;
6851 case 'l': func
= (fptr_T
)do_lower
;
6853 case 'L': func
= (fptr_T
)do_Lower
;
6856 case 'E': func
= (fptr_T
)NULL
;
6861 if (no
< 0) /* Ordinary character. */
6863 if (c
== K_SPECIAL
&& src
[0] != NUL
&& src
[1] != NUL
)
6865 /* Copy a specialy key as-is. */
6880 if (c
== '\\' && *src
!= NUL
)
6882 /* Check for abbreviations -- webb */
6885 case 'r': c
= CAR
; ++src
; break;
6886 case 'n': c
= NL
; ++src
; break;
6887 case 't': c
= TAB
; ++src
; break;
6888 /* Oh no! \e already has meaning in subst pat :-( */
6889 /* case 'e': c = ESC; ++src; break; */
6890 case 'b': c
= Ctrl_H
; ++src
; break;
6892 /* If "backslash" is TRUE the backslash will be removed
6893 * later. Used to insert a literal CR. */
6894 default: if (backslash
)
6905 c
= mb_ptr2char(src
- 1);
6908 /* Write to buffer, if copy is set. */
6909 if (func
== (fptr_T
)NULL
) /* just copy */
6912 /* Turbo C complains without the typecast */
6913 func
= (fptr_T
)(func(&cc
, c
));
6918 src
+= mb_ptr2len(src
- 1) - 1;
6920 mb_char2bytes(cc
, dst
);
6921 dst
+= mb_char2len(cc
) - 1;
6933 clnum
= reg_mmatch
->startpos
[no
].lnum
;
6934 if (clnum
< 0 || reg_mmatch
->endpos
[no
].lnum
< 0)
6938 s
= reg_getline(clnum
) + reg_mmatch
->startpos
[no
].col
;
6939 if (reg_mmatch
->endpos
[no
].lnum
== clnum
)
6940 len
= reg_mmatch
->endpos
[no
].col
6941 - reg_mmatch
->startpos
[no
].col
;
6943 len
= (int)STRLEN(s
);
6948 s
= reg_match
->startp
[no
];
6949 if (reg_match
->endp
[no
] == NULL
)
6952 len
= (int)(reg_match
->endp
[no
] - s
);
6962 if (reg_mmatch
->endpos
[no
].lnum
== clnum
)
6967 s
= reg_getline(++clnum
);
6968 if (reg_mmatch
->endpos
[no
].lnum
== clnum
)
6969 len
= reg_mmatch
->endpos
[no
].col
;
6971 len
= (int)STRLEN(s
);
6976 else if (*s
== NUL
) /* we hit NUL. */
6984 if (backslash
&& (*s
== CAR
|| *s
== '\\'))
6987 * Insert a backslash in front of a CR, otherwise
6988 * it will be replaced by a line break.
6989 * Number of backslashes will be halved later,
7008 if (func
== (fptr_T
)NULL
) /* just copy */
7011 /* Turbo C complains without the typecast */
7012 func
= (fptr_T
)(func(&cc
, c
));
7017 int l
= mb_ptr2len(s
) - 1;
7022 mb_char2bytes(cc
, dst
);
7023 dst
+= mb_char2len(cc
) - 1;
7044 return (int)((dst
- dest
) + 1);
7049 * Used for the submatch() function: get the string from tne n'th submatch in
7051 * Returns NULL when not in a ":s" command and for a non-existing submatch.
7057 char_u
*retval
= NULL
;
7063 if (!can_f_submatch
|| no
< 0)
7066 if (submatch_match
== NULL
)
7069 * First round: compute the length and allocate memory.
7070 * Second round: copy the text.
7072 for (round
= 1; round
<= 2; ++round
)
7074 lnum
= submatch_mmatch
->startpos
[no
].lnum
;
7075 if (lnum
< 0 || submatch_mmatch
->endpos
[no
].lnum
< 0)
7078 s
= reg_getline(lnum
) + submatch_mmatch
->startpos
[no
].col
;
7079 if (s
== NULL
) /* anti-crash check, cannot happen? */
7081 if (submatch_mmatch
->endpos
[no
].lnum
== lnum
)
7083 /* Within one line: take form start to end col. */
7084 len
= submatch_mmatch
->endpos
[no
].col
7085 - submatch_mmatch
->startpos
[no
].col
;
7087 vim_strncpy(retval
, s
, len
);
7092 /* Multiple lines: take start line from start col, middle
7093 * lines completely and end line up to end col. */
7094 len
= (int)STRLEN(s
);
7102 while (lnum
< submatch_mmatch
->endpos
[no
].lnum
)
7104 s
= reg_getline(lnum
++);
7106 STRCPY(retval
+ len
, s
);
7107 len
+= (int)STRLEN(s
);
7113 STRNCPY(retval
+ len
, reg_getline(lnum
),
7114 submatch_mmatch
->endpos
[no
].col
);
7115 len
+= submatch_mmatch
->endpos
[no
].col
;
7123 retval
= lalloc((long_u
)len
, TRUE
);
7131 if (submatch_match
->endp
[no
] == NULL
)
7135 s
= submatch_match
->startp
[no
];
7136 retval
= vim_strnsave(s
, (int)(submatch_match
->endp
[no
] - s
));