2 * Copyright (c) 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1992, 1993, 1994, 1995, 1996
5 * Keith Bostic. All rights reserved.
7 * See the LICENSE file for redistribution information.
12 #include <sys/types.h>
13 #include <sys/queue.h>
16 #include <bitstring.h>
25 #include "../common/common.h"
28 #define SUB_FIRST 0x01 /* The 'r' flag isn't reasonable. */
29 #define SUB_MUSTSETR 0x02 /* The 'r' flag is required. */
31 static int re_conv(SCR *, CHAR_T **, size_t *, int *);
32 static int re_cscope_conv(SCR *, CHAR_T **, size_t *, int *);
33 static int re_sub(SCR *,
34 CHAR_T *, CHAR_T **, size_t *, size_t *, regmatch_t [10]);
35 static int re_tag_conv(SCR *, CHAR_T **, size_t *, int *);
36 static int s(SCR *, EXCMD *, CHAR_T *, regex_t *, u_int);
40 * [line [,line]] s[ubstitute] [[/;]pat[/;]/repl[/;] [cgr] [count] [#lp]]
42 * Substitute on lines matching a pattern.
44 * PUBLIC: int ex_s(SCR *, EXCMD *);
47 ex_s(SCR *sp, EXCMD *cmdp)
53 CHAR_T *bp, *p, *ptrn, *rep, *t;
56 * Skip leading white space.
59 * Historic vi allowed any non-alphanumeric to serve as the
60 * substitution command delimiter.
63 * If the arguments are empty, it's the same as &, i.e. we
64 * repeat the last substitution.
68 for (p = cmdp->argv[0]->bp,
69 len = cmdp->argv[0]->len; len > 0; --len, ++p) {
74 subagain: return (ex_subagain(sp, cmdp));
77 if (is09azAZ(delim) || delim == '\\')
78 return (s(sp, cmdp, p, &sp->subre_c, SUB_MUSTSETR));
82 * The full-blown substitute command reset the remembered
83 * state of the 'c' and 'g' suffices.
85 sp->c_suffix = sp->g_suffix = 0;
88 * Get the pattern string, toss escaping characters.
91 * Historic vi accepted any of the following forms:
93 * :s/abc/def/ change "abc" to "def"
94 * :s/abc/def change "abc" to "def"
95 * :s/abc/ delete "abc"
100 * Only toss an escaping character if it escapes a delimiter.
101 * This means that "s/A/\\\\f" replaces "A" with "\\f". It
102 * would be nice to be more regular, i.e. for each layer of
103 * escaping a single escaping character is removed, but that's
104 * not how the historic vi worked.
106 for (ptrn = t = p;;) {
107 if (p[0] == '\0' || p[0] == delim) {
112 * Nul terminate the pattern string -- it's passed
113 * to regcomp which doesn't understand anything else.
121 else if (p[1] == '\\')
128 * If the pattern string is empty, use the last RE (not just the
129 * last substitution RE).
132 if (sp->re == NULL) {
133 ex_emsg(sp, NULL, EXM_NOPREVRE);
137 /* Re-compile the RE if necessary. */
138 if (!F_ISSET(sp, SC_RE_SEARCH) &&
139 re_compile(sp, sp->re, sp->re_len,
140 NULL, NULL, &sp->re_c, RE_C_SEARCH))
146 * Compile the RE. Historic practice is that substitutes set
147 * the search direction as well as both substitute and search
148 * RE's. We compile the RE twice, as we don't want to bother
149 * ref counting the pattern string and (opaque) structure.
151 if (re_compile(sp, ptrn, t - ptrn, &sp->re,
152 &sp->re_len, &sp->re_c, RE_C_SEARCH))
154 if (re_compile(sp, ptrn, t - ptrn, &sp->subre,
155 &sp->subre_len, &sp->subre_c, RE_C_SUBST))
159 sp->searchdir = FORWARD;
164 * Get the replacement string.
166 * The special character & (\& if O_MAGIC not set) matches the
167 * entire RE. No handling of & is required here, it's done by
170 * The special character ~ (\~ if O_MAGIC not set) inserts the
171 * previous replacement string into this replacement string.
172 * Count ~'s to figure out how much space we need. We could
173 * special case nonexistent last patterns or whether or not
174 * O_MAGIC is set, but it's probably not worth the effort.
178 * Only toss an escaping character if it escapes a delimiter or
179 * if O_MAGIC is set and it escapes a tilde.
182 * If the entire replacement pattern is "%", then use the last
183 * replacement pattern. This semantic was added to vi in System
184 * V and then percolated elsewhere, presumably around the time
185 * that it was added to their version of ed(1).
187 if (p[0] == '\0' || p[0] == delim) {
193 } else if (p[0] == '%' && (p[1] == '\0' || p[1] == delim))
194 p += p[1] == delim ? 2 : 1;
196 for (rep = p, len = 0;
197 p[0] != '\0' && p[0] != delim; ++p, ++len)
200 GET_SPACE_RETW(sp, bp, blen, len);
201 for (t = bp, len = 0, p = rep;;) {
202 if (p[0] == '\0' || p[0] == delim) {
210 else if (p[1] == '\\') {
213 } else if (p[1] == '~') {
215 if (!O_ISSET(sp, O_MAGIC))
218 } else if (p[0] == '~' && O_ISSET(sp, O_MAGIC)) {
220 MEMCPY(t, sp->repl, sp->repl_len);
228 if ((sp->repl_len = len) != 0) {
230 MALLOC(sp, sp->repl, len * sizeof(CHAR_T));
231 if (sp->repl == NULL) {
232 FREE_SPACEW(sp, bp, blen);
235 MEMCPY(sp->repl, bp, len);
237 FREE_SPACEW(sp, bp, blen);
239 return (s(sp, cmdp, p, re, flags));
244 * [line [,line]] & [cgr] [count] [#lp]]
246 * Substitute using the last substitute RE and replacement pattern.
248 * PUBLIC: int ex_subagain(SCR *, EXCMD *);
251 ex_subagain(SCR *sp, EXCMD *cmdp)
253 if (sp->subre == NULL) {
254 ex_emsg(sp, NULL, EXM_NOPREVRE);
257 if (!F_ISSET(sp, SC_RE_SUBST) &&
258 re_compile(sp, sp->subre, sp->subre_len,
259 NULL, NULL, &sp->subre_c, RE_C_SUBST))
262 cmdp, cmdp->argc ? cmdp->argv[0]->bp : NULL, &sp->subre_c, 0));
267 * [line [,line]] ~ [cgr] [count] [#lp]]
269 * Substitute using the last RE and last substitute replacement pattern.
271 * PUBLIC: int ex_subtilde(SCR *, EXCMD *);
274 ex_subtilde(SCR *sp, EXCMD *cmdp)
276 if (sp->re == NULL) {
277 ex_emsg(sp, NULL, EXM_NOPREVRE);
280 if (!F_ISSET(sp, SC_RE_SEARCH) && re_compile(sp, sp->re,
281 sp->re_len, NULL, NULL, &sp->re_c, RE_C_SEARCH))
284 cmdp, cmdp->argc ? cmdp->argv[0]->bp : NULL, &sp->re_c, 0));
289 * Do the substitution. This stuff is *really* tricky. There are lots of
290 * special cases, and general nastiness. Don't mess with it unless you're
293 * The nasty part of the substitution is what happens when the replacement
294 * string contains newlines. It's a bit tricky -- consider the information
295 * that has to be retained for "s/f\(o\)o/^M\1^M\1/". The solution here is
296 * to build a set of newline offsets which we use to break the line up later,
297 * when the replacement is done. Don't change it unless you're *damned*
300 #define NEEDNEWLINE(sp) do { \
301 if (sp->newl_len == sp->newl_cnt) { \
302 sp->newl_len += 25; \
303 REALLOC(sp, sp->newl, size_t *, \
304 sp->newl_len * sizeof(size_t)); \
305 if (sp->newl == NULL) { \
312 #define BUILD(sp, l, len) do { \
313 if (lbclen + (len) > lblen) { \
314 lblen = p2roundup(MAX(lbclen + (len), 256)); \
315 REALLOC(sp, lb, CHAR_T *, lblen * sizeof(CHAR_T)); \
321 MEMCPY(lb + lbclen, l, len); \
325 #define NEEDSP(sp, len, pnt) do { \
326 if (lbclen + (len) > lblen) { \
327 lblen = p2roundup(MAX(lbclen + (len), 256)); \
328 REALLOC(sp, lb, CHAR_T *, lblen * sizeof(CHAR_T)); \
338 s(SCR *sp, EXCMD *cmdp, CHAR_T *s, regex_t *re, u_int flags)
342 TEXTH tiq[] = {{ 0 }};
343 recno_t elno, lno, slno;
345 regmatch_t match[10];
346 size_t blen, cnt, last, lbclen, lblen, len, llen;
347 size_t offset, saved_offset, scno;
348 int cflag, lflag, nflag, pflag, rflag;
349 int didsub, do_eol_match, eflags, empty_ok, eval;
350 int linechanged, matched, quit, rval;
361 * Historically, the 'g' and 'c' suffices were always toggled as flags,
362 * so ":s/A/B/" was the same as ":s/A/B/ccgg". If O_EDCOMPATIBLE was
363 * not set, they were initialized to 0 for all substitute commands. If
364 * O_EDCOMPATIBLE was set, they were initialized to 0 only if the user
365 * specified substitute/replacement patterns (see ex_s()).
367 if (!O_ISSET(sp, O_EDCOMPATIBLE))
368 sp->c_suffix = sp->g_suffix = 0;
371 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
372 * it only displayed the last change. I'd disallow them, but they are
373 * useful in combination with the [v]global commands. In the current
374 * model the problem is combining them with the 'c' flag -- the screen
375 * would have to flip back and forth between the confirm screen and the
376 * ex print screen, which would be pretty awful. We do display all
377 * changes, though, for what that's worth.
380 * Historic vi was fairly strict about the order of "options", the
381 * count, and "flags". I'm somewhat fuzzy on the difference between
382 * options and flags, anyway, so this is a simpler approach, and we
383 * just take it them in whatever order the user gives them. (The ex
384 * usage statement doesn't reflect this.)
386 cflag = lflag = nflag = pflag = rflag = 0;
389 for (lno = OOBLNO; *s != '\0'; ++s)
400 case '0': case '1': case '2': case '3': case '4':
401 case '5': case '6': case '7': case '8': case '9':
405 nret = nget_uslong(&ul, s, &s, 10);
407 if (*s == '\0') /* Loop increment correction. */
409 if (nret != NUM_OK) {
410 if (nret == NUM_OVER)
411 msgq(sp, M_ERR, "153|Count overflow");
412 else if (nret == NUM_UNDER)
413 msgq(sp, M_ERR, "154|Count underflow");
415 msgq(sp, M_SYSERR, NULL);
419 * In historic vi, the count was inclusive from the
422 cmdp->addr1.lno = cmdp->addr2.lno;
423 cmdp->addr2.lno += lno - 1;
424 if (!db_exist(sp, cmdp->addr2.lno) &&
425 db_last(sp, &cmdp->addr2.lno))
432 sp->c_suffix = !sp->c_suffix;
434 /* Ex text structure initialization. */
435 if (F_ISSET(sp, SC_EX))
439 sp->g_suffix = !sp->g_suffix;
448 if (LF_ISSET(SUB_FIRST)) {
450 "155|Regular expression specified; r flag meaningless");
453 if (!F_ISSET(sp, SC_RE_SEARCH)) {
454 ex_emsg(sp, NULL, EXM_NOPREVRE);
464 if (*s != '\0' || (!rflag && LF_ISSET(SUB_MUSTSETR))) {
465 usage: ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE);
469 noargs: if (F_ISSET(sp, SC_VI) && sp->c_suffix && (lflag || nflag || pflag)) {
471 "156|The #, l and p flags may not be combined with the c flag in vi mode");
476 * bp: if interactive, line cache
477 * blen: if interactive, line cache length
478 * lb: build buffer pointer.
479 * lbclen: current length of built buffer.
480 * lblen; length of build buffer.
483 blen = lbclen = lblen = 0;
485 /* For each line... */
486 lno = cmdp->addr1.lno == 0 ? 1 : cmdp->addr1.lno;
487 for (matched = quit = 0,
488 elno = cmdp->addr2.lno; !quit && lno <= elno; ++lno) {
490 /* Someone's unhappy, time to stop. */
495 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
499 * Make a local copy if doing confirmation -- when calling
500 * the confirm routine we're likely to lose the cached copy.
504 GET_SPACE_RETW(sp, bp, blen, llen);
506 ADD_SPACE_RETW(sp, bp, blen, llen);
511 /* Start searching from the beginning. */
515 /* Reset the build buffer offset. */
518 /* Reset empty match flag. */
522 * We don't want to have to do a setline if the line didn't
523 * change -- keep track of whether or not this line changed.
524 * If doing confirmations, don't want to keep setting the
525 * line if change is refused -- keep track of substitutions.
527 didsub = linechanged = 0;
529 /* New line, do an EOL match. */
532 /* It's not nul terminated, but we pretend it is. */
533 eflags = REG_STARTEND;
536 * The search area is from s + offset to the EOL.
538 * Generally, match[0].rm_so is the offset of the start
539 * of the match from the start of the search, and offset
540 * is the offset of the start of the last search.
542 nextmatch: match[0].rm_so = 0;
543 match[0].rm_eo = len;
545 /* Get the next match. */
546 eval = regexec(re, s + offset, 10, match, eflags);
549 * There wasn't a match or if there was an error, deal with
550 * it. If there was a previous match in this line, resolve
551 * the changes into the database. Otherwise, just move on.
553 if (eval == REG_NOMATCH)
556 re_error(sp, eval, re);
561 /* Only the first search can match an anchored expression. */
562 eflags |= REG_NOTBOL;
566 * It's possible to match 0-length strings -- for example, the
567 * command s;a*;X;, when matched against the string "aabb" will
568 * result in "XbXbX", i.e. the matches are "aa", the space
569 * between the b's and the space between the b's and the end of
570 * the string. There is a similar space between the beginning
571 * of the string and the a's. The rule that we use (because vi
572 * historically used it) is that any 0-length match, occurring
573 * immediately after a match, is ignored. Otherwise, the above
574 * example would have resulted in "XXbXbX". Another example is
575 * incorrectly using " *" to replace groups of spaces with one
578 * The way we do this is that if we just had a successful match,
579 * the starting offset does not skip characters, and the match
580 * is empty, ignore the match and move forward. If there's no
581 * more characters in the string, we were attempting to match
582 * after the last character, so quit.
584 if (!empty_ok && match[0].rm_so == 0 && match[0].rm_eo == 0) {
588 BUILD(sp, s + offset, 1);
594 /* Confirm change. */
597 * Set the cursor position for confirmation. Note,
598 * if we matched on a '$', the cursor may be past
601 from.lno = to.lno = lno;
602 from.cno = match[0].rm_so + offset;
603 to.cno = match[0].rm_eo + offset;
605 * Both ex and vi have to correct for a change before
606 * the first character in the line.
609 from.cno = to.cno = 0;
610 if (F_ISSET(sp, SC_VI)) {
612 * Only vi has to correct for a change after
613 * the last character in the line.
616 * It would be nice to change the vi code so
617 * that we could display a cursor past EOL.
621 if (from.cno >= llen)
626 if (vs_refresh(sp, 1))
629 vs_update(sp, msg_cat(sp,
630 "169|Confirm change? [n]", NULL), NULL);
632 if (v_event_get(sp, &ev, 0, 0))
634 switch (ev.e_event) {
642 v_event_err(sp, &ev);
646 if (ex_print(sp, cmdp, &from, &to, 0) ||
647 ex_scprint(sp, &from, &to))
649 if (ex_txt(sp, tiq, 0, TXT_CR))
651 ev.e_c = TAILQ_FIRST(tiq)->lb[0];
660 BUILD(sp, s +offset, match[0].rm_eo);
663 /* Set the quit/interrupted flags. */
665 F_SET(sp->gp, G_INTERRUPTED);
668 * Resolve any changes, then return to (and
669 * exit from) the main loop.
676 * Set the cursor to the last position changed, converting
677 * from 1-based to 0-based.
680 sp->cno = match[0].rm_so;
682 /* Copy the bytes before the match into the build buffer. */
683 BUILD(sp, s + offset, match[0].rm_so);
685 /* Substitute the matching bytes. */
687 if (re_sub(sp, s + offset, &lb, &lbclen, &lblen, match))
690 /* Set the change flag so we know this line was modified. */
693 /* Move past the matched bytes. */
694 skip: offset += match[0].rm_eo;
695 len -= match[0].rm_eo;
697 /* A match cannot be followed by an empty pattern. */
701 * If doing a global change with confirmation, we have to
702 * update the screen. The basic idea is to store the line
703 * so the screen update routines can find it, and restart.
705 if (didsub && sp->c_suffix && sp->g_suffix) {
707 * The new search offset will be the end of the
710 saved_offset = lbclen;
712 /* Copy the rest of the line. */
714 BUILD(sp, s + offset, len);
716 /* Set the new offset. */
717 offset = saved_offset;
719 /* Store inserted lines, adjusting the build buffer. */
723 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
724 if (db_insert(sp, lno,
725 lb + last, sp->newl[cnt] - last))
727 last = sp->newl[cnt] + 1;
728 ++sp->rptlines[L_ADDED];
735 /* Store and retrieve the line. */
736 if (db_set(sp, lno, lb + last, lbclen))
738 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
740 ADD_SPACE_RETW(sp, bp, blen, llen);
745 /* Restart the build. */
747 BUILD(sp, s, offset);
750 * If we haven't already done the after-the-string
751 * match, do one. Set REG_NOTEOL so the '$' pattern
758 eflags |= REG_NOTEOL;
766 * If at the end of the string, do a test for the after
767 * the string match. Set REG_NOTEOL so the '$' pattern
770 if (sp->g_suffix && do_eol_match) {
773 eflags |= REG_NOTEOL;
778 endmatch: if (!linechanged)
781 /* Copy any remaining bytes into the build buffer. */
783 BUILD(sp, s + offset, len);
785 /* Store inserted lines, adjusting the build buffer. */
789 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
791 lno, lb + last, sp->newl[cnt] - last))
793 last = sp->newl[cnt] + 1;
794 ++sp->rptlines[L_ADDED];
800 /* Store the changed line. */
801 if (db_set(sp, lno, lb + last, lbclen))
804 /* Update changed line counter. */
805 if (sp->rptlchange != lno) {
806 sp->rptlchange = lno;
807 ++sp->rptlines[L_CHANGED];
812 * Display as necessary. Historic practice is to only
813 * display the last line of a line split into multiple
816 if (lflag || nflag || pflag) {
817 from.lno = to.lno = lno;
818 from.cno = to.cno = 0;
820 (void)ex_print(sp, cmdp, &from, &to, E_C_LIST);
822 (void)ex_print(sp, cmdp, &from, &to, E_C_HASH);
824 (void)ex_print(sp, cmdp, &from, &to, E_C_PRINT);
830 * Historically, vi attempted to leave the cursor at the same place if
831 * the substitution was done at the current cursor position. Otherwise
832 * it moved it to the first non-blank of the last line changed. There
833 * were some problems: for example, :s/$/foo/ with the cursor on the
834 * last character of the line left the cursor on the last character, or
835 * the & command with multiple occurrences of the matching string in the
836 * line usually left the cursor in a fairly random position.
838 * We try to do the same thing, with the exception that if the user is
839 * doing substitution with confirmation, we move to the last line about
840 * which the user was consulted, as opposed to the last line that they
841 * actually changed. This prevents a screen flash if the user doesn't
842 * change many of the possible lines.
844 if (!sp->c_suffix && (sp->lno != slno || sp->cno != scno)) {
846 (void)nonblank(sp, sp->lno, &sp->cno);
850 * If not in a global command, and nothing matched, say so.
851 * Else, if none of the lines displayed, put something up.
855 if (!F_ISSET(sp, SC_EX_GLOBAL)) {
856 msgq(sp, M_ERR, "157|No match found");
859 } else if (!lflag && !nflag && !pflag)
860 F_SET(cmdp, E_AUTOPRINT);
867 FREE_SPACEW(sp, bp, blen);
876 * PUBLIC: int re_compile(SCR *,
877 * PUBLIC: CHAR_T *, size_t, CHAR_T **, size_t *, regex_t *, u_int);
880 re_compile(SCR *sp, CHAR_T *ptrn, size_t plen, CHAR_T **ptrnp, size_t *lenp, regex_t *rep, u_int flags)
883 int reflags, replaced, rval;
888 if (!LF_ISSET(RE_C_CSCOPE | RE_C_TAG)) {
889 if (O_ISSET(sp, O_EXTENDED))
890 reflags |= REG_EXTENDED;
891 if (O_ISSET(sp, O_IGNORECASE))
892 reflags |= REG_ICASE;
893 if (O_ISSET(sp, O_ICLOWER)) {
894 for (p = ptrn, len = plen; len > 0; ++p, --len)
898 reflags |= REG_ICASE;
902 /* If we're replacing a saved value, clear the old one. */
903 if (LF_ISSET(RE_C_SEARCH) && F_ISSET(sp, SC_RE_SEARCH)) {
905 F_CLR(sp, SC_RE_SEARCH);
907 if (LF_ISSET(RE_C_SUBST) && F_ISSET(sp, SC_RE_SUBST)) {
908 regfree(&sp->subre_c);
909 F_CLR(sp, SC_RE_SUBST);
913 * If we're saving the string, it's a pattern we haven't seen before,
914 * so convert the vi-style RE's to POSIX 1003.2 RE's. Save a copy for
915 * later recompilation. Free any previously saved value.
919 if (LF_ISSET(RE_C_CSCOPE)) {
920 if (re_cscope_conv(sp, &ptrn, &plen, &replaced))
924 * Currently, the match-any-<blank> expression used in
925 * re_cscope_conv() requires extended RE's. This may
926 * not be right or safe.
928 reflags |= REG_EXTENDED;
929 } else if (LF_ISSET(RE_C_TAG)) {
930 if (re_tag_conv(sp, &ptrn, &plen, &replaced))
933 if (re_conv(sp, &ptrn, &plen, &replaced))
936 /* Discard previous pattern. */
944 * Copy the string into allocated memory.
947 * Regcomp isn't 8-bit clean, so the pattern is nul-terminated
948 * for now. There's just no other solution.
950 MALLOC(sp, *ptrnp, (plen + 1) * sizeof(CHAR_T));
951 if (*ptrnp != NULL) {
952 MEMCPY(*ptrnp, ptrn, plen);
953 (*ptrnp)[plen] = '\0';
956 /* Free up conversion-routine-allocated memory. */
958 FREE_SPACEW(sp, ptrn, 0);
968 * Regcomp isn't 8-bit clean, so we just lost if the pattern
969 * contained a nul. Bummer!
971 if ((rval = regcomp(rep, ptrn, /* plen, */ reflags)) != 0) {
972 if (!LF_ISSET(RE_C_SILENT))
973 re_error(sp, rval, rep);
977 if (LF_ISSET(RE_C_SEARCH))
978 F_SET(sp, SC_RE_SEARCH);
979 if (LF_ISSET(RE_C_SUBST))
980 F_SET(sp, SC_RE_SUBST);
987 * Convert vi's regular expressions into something that the
988 * the POSIX 1003.2 RE functions can handle.
990 * There are three conversions we make to make vi's RE's (specifically
991 * the global, search, and substitute patterns) work with POSIX RE's.
993 * 1: If O_MAGIC is not set, strip backslashes from the magic character
994 * set (.[*~) that have them, and add them to the ones that don't.
995 * 2: If O_MAGIC is not set, the string "\~" is replaced with the text
996 * from the last substitute command's replacement string. If O_MAGIC
997 * is set, it's the string "~".
998 * 3: The pattern \<ptrn\> does "word" searches, convert it to use the
1002 * This doesn't exactly match the historic behavior of vi because we do
1003 * the ~ substitution before calling the RE engine, so magic characters
1004 * in the replacement string will be expanded by the RE engine, and they
1005 * weren't historically. It's a bug.
1008 re_conv(SCR *sp, CHAR_T **ptrnp, size_t *plenp, int *replacedp)
1010 size_t blen, len, needlen;
1015 * First pass through, we figure out how much space we'll need.
1016 * We do it in two passes, on the grounds that most of the time
1017 * the user is doing a search and won't have magic characters.
1018 * That way we can skip most of the memory allocation and copies.
1021 for (p = *ptrnp, len = *plenp, needlen = 0; len > 0; ++p, --len)
1029 needlen += RE_WSTART_LEN + 1;
1033 needlen += RE_WSTOP_LEN + 1;
1036 if (!O_ISSET(sp, O_MAGIC)) {
1038 needlen += sp->repl_len;
1044 if (!O_ISSET(sp, O_MAGIC)) {
1056 if (O_ISSET(sp, O_MAGIC)) {
1058 needlen += sp->repl_len;
1064 if (!O_ISSET(sp, O_MAGIC)) {
1079 /* Get enough memory to hold the final pattern. */
1081 GET_SPACE_RETW(sp, bp, blen, needlen);
1083 for (p = *ptrnp, len = *plenp, t = bp; len > 0; ++p, --len)
1091 RE_WSTART, RE_WSTART_LEN);
1096 RE_WSTOP, RE_WSTOP_LEN);
1100 if (O_ISSET(sp, O_MAGIC))
1104 sp->repl, sp->repl_len);
1111 if (O_ISSET(sp, O_MAGIC))
1123 if (O_ISSET(sp, O_MAGIC)) {
1124 MEMCPY(t, sp->repl, sp->repl_len);
1132 if (!O_ISSET(sp, O_MAGIC))
1148 * Convert a tags search path into something that the POSIX
1149 * 1003.2 RE functions can handle.
1152 re_tag_conv(SCR *sp, CHAR_T **ptrnp, size_t *plenp, int *replacedp)
1160 /* Max memory usage is 2 times the length of the string. */
1162 GET_SPACE_RETW(sp, bp, blen, len * 2);
1167 /* If the last character is a '/' or '?', we just strip it. */
1168 if (len > 0 && (p[len - 1] == '/' || p[len - 1] == '?'))
1171 /* If the next-to-last or last character is a '$', it's magic. */
1172 if (len > 0 && p[len - 1] == '$') {
1178 /* If the first character is a '/' or '?', we just strip it. */
1179 if (len > 0 && (p[0] == '/' || p[0] == '?')) {
1184 /* If the first or second character is a '^', it's magic. */
1191 * Escape every other magic character we can find, meanwhile stripping
1192 * the backslashes ctags inserts when escaping the search delimiter
1195 for (; len > 0; --len) {
1196 if (p[0] == '\\' && (p[1] == '/' || p[1] == '?')) {
1199 } else if (STRCHR(L("^.[]$*"), p[0]))
1213 * Convert a cscope search path into something that the POSIX
1214 * 1003.2 RE functions can handle.
1217 re_cscope_conv(SCR *sp, CHAR_T **ptrnp, size_t *plenp, int *replacedp)
1219 size_t blen, len, nspaces;
1226 * Each space in the source line printed by cscope represents an
1227 * arbitrary sequence of spaces, tabs, and comments.
1229 #define CSCOPE_RE_SPACE "([ \t]|/\\*([^*]|\\*/)*\\*/)*"
1230 #define CSCOPE_LEN sizeof(CSCOPE_RE_SPACE) - 1
1231 CHAR2INT(sp, CSCOPE_RE_SPACE, CSCOPE_LEN, wp, wlen);
1232 for (nspaces = 0, p = *ptrnp, len = *plenp; len > 0; ++p, --len)
1237 * Allocate plenty of space:
1238 * the string, plus potential escaping characters;
1239 * nspaces + 2 copies of CSCOPE_RE_SPACE;
1240 * ^, $, nul terminator characters.
1243 len = (p - *ptrnp) * 2 + (nspaces + 2) * sizeof(CSCOPE_RE_SPACE) + 3;
1244 GET_SPACE_RETW(sp, bp, blen, len);
1250 MEMCPY(t, wp, wlen);
1253 for (len = *plenp; len > 0; ++p, --len)
1255 MEMCPY(t, wp, wlen);
1258 if (STRCHR(L("\\^.[]$*+?()|{}"), *p))
1263 MEMCPY(t, wp, wlen);
1274 * Report a regular expression error.
1276 * PUBLIC: void re_error(SCR *, int, regex_t *);
1279 re_error(SCR *sp, int errcode, regex_t *preg)
1284 s = regerror(errcode, preg, "", 0);
1287 (void)regerror(errcode, preg, oe, s);
1288 msgq(sp, M_ERR, "RE error: %s", oe);
1295 * Do the substitution for a regular expression.
1300 CHAR_T *ip, /* Input line. */
1304 regmatch_t match[10])
1306 enum { C_NOTSET, C_LOWER, C_ONELOWER, C_ONEUPPER, C_UPPER } conv;
1307 size_t lbclen, lblen; /* Local copies. */
1308 size_t mlen; /* Match length. */
1309 size_t rpl; /* Remaining replacement length. */
1310 CHAR_T *rp; /* Replacement pointer. */
1312 int no; /* Match replacement offset. */
1313 CHAR_T *p, *t; /* Buffer pointers. */
1314 CHAR_T *lb; /* Local copies. */
1316 lb = *lbp; /* Get local copies. */
1323 * There are some special sequences that vi provides in the
1324 * replacement patterns.
1325 * & string the RE matched (\& if nomagic set)
1326 * \# n-th regular subexpression
1327 * \E end \U, \L conversion
1328 * \e end \U, \L conversion
1329 * \l convert the next character to lower-case
1330 * \L convert to lower-case, until \E, \e, or end of replacement
1331 * \u convert the next character to upper-case
1332 * \U convert to upper-case, until \E, \e, or end of replacement
1334 * Otherwise, since this is the lowest level of replacement, discard
1335 * all escaping characters. This (hopefully) matches historic practice.
1337 #define OUTCH(ch, nltrans) do { \
1338 ARG_CHAR_T __ch = (ch); \
1339 e_key_t __value = KEY_VAL(sp, __ch); \
1340 if (nltrans && (__value == K_CR || __value == K_NL)) { \
1342 sp->newl[sp->newl_cnt++] = lbclen; \
1343 } else if (conv != C_NOTSET) { \
1349 if (ISUPPER(__ch)) \
1350 __ch = TOLOWER(__ch); \
1356 if (ISLOWER(__ch)) \
1357 __ch = TOUPPER(__ch); \
1368 for (rp = sp->repl, rpl = sp->repl_len, p = lb + lbclen; rpl--;) {
1369 switch (ch = *rp++) {
1371 if (O_ISSET(sp, O_MAGIC)) {
1383 if (!O_ISSET(sp, O_MAGIC)) {
1388 case '0': case '1': case '2': case '3': case '4':
1389 case '5': case '6': case '7': case '8': case '9':
1391 subzero: if (match[no].rm_so == -1 ||
1392 match[no].rm_eo == -1)
1394 mlen = match[no].rm_eo - match[no].rm_so;
1395 for (t = ip + match[no].rm_so; mlen--; ++t)
1430 *lbp = lb; /* Update caller's information. */