only clean out gs when last window goes
[nvi.git] / ex / ex_subst.c
blobdd81a7f8f56e7a17a91f8b2829451d5d276b4c67
1 /*-
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.
8 */
10 #include "config.h"
12 #ifndef lint
13 static const char sccsid[] = "$Id: ex_subst.c,v 10.42 2000/06/27 17:19:06 skimo Exp $ (Berkeley) $Date: 2000/06/27 17:19:06 $";
14 #endif /* not lint */
16 #include <sys/types.h>
17 #include <sys/queue.h>
18 #include <sys/time.h>
20 #include <bitstring.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
29 #include "../common/common.h"
30 #include "../vi/vi.h"
32 #define SUB_FIRST 0x01 /* The 'r' flag isn't reasonable. */
33 #define SUB_MUSTSETR 0x02 /* The 'r' flag is required. */
35 static int re_conv __P((SCR *, char **, size_t *, int *));
36 static int re_cscope_conv __P((SCR *, char **, size_t *, int *));
37 static int re_sub __P((SCR *,
38 char *, char **, size_t *, size_t *, regmatch_t [10]));
39 static int re_tag_conv __P((SCR *, char **, size_t *, int *));
40 static int s __P((SCR *, EXCMD *, char *, regex_t *, u_int));
43 * ex_s --
44 * [line [,line]] s[ubstitute] [[/;]pat[/;]/repl[/;] [cgr] [count] [#lp]]
46 * Substitute on lines matching a pattern.
48 * PUBLIC: int ex_s __P((SCR *, EXCMD *));
50 int
51 ex_s(sp, cmdp)
52 SCR *sp;
53 EXCMD *cmdp;
55 regex_t *re;
56 size_t blen, len;
57 u_int flags;
58 int delim;
59 char *bp, *ptrn, *rep, *p, *t;
62 * Skip leading white space.
64 * !!!
65 * Historic vi allowed any non-alphanumeric to serve as the
66 * substitution command delimiter.
68 * !!!
69 * If the arguments are empty, it's the same as &, i.e. we
70 * repeat the last substitution.
72 if (cmdp->argc == 0)
73 goto subagain;
74 for (p = cmdp->argv[0]->bp,
75 len = cmdp->argv[0]->len; len > 0; --len, ++p) {
76 if (!isblank(*p))
77 break;
79 if (len == 0)
80 subagain: return (ex_subagain(sp, cmdp));
82 delim = *p++;
83 if (isalnum(delim) || delim == '\\')
84 return (s(sp, cmdp, p, &sp->subre_c, SUB_MUSTSETR));
87 * !!!
88 * The full-blown substitute command reset the remembered
89 * state of the 'c' and 'g' suffices.
91 sp->c_suffix = sp->g_suffix = 0;
94 * Get the pattern string, toss escaping characters.
96 * !!!
97 * Historic vi accepted any of the following forms:
99 * :s/abc/def/ change "abc" to "def"
100 * :s/abc/def change "abc" to "def"
101 * :s/abc/ delete "abc"
102 * :s/abc delete "abc"
104 * QUOTING NOTE:
106 * Only toss an escaping character if it escapes a delimiter.
107 * This means that "s/A/\\\\f" replaces "A" with "\\f". It
108 * would be nice to be more regular, i.e. for each layer of
109 * escaping a single escaping character is removed, but that's
110 * not how the historic vi worked.
112 for (ptrn = t = p;;) {
113 if (p[0] == '\0' || p[0] == delim) {
114 if (p[0] == delim)
115 ++p;
117 * !!!
118 * Nul terminate the pattern string -- it's passed
119 * to regcomp which doesn't understand anything else.
121 *t = '\0';
122 break;
124 if (p[0] == '\\')
125 if (p[1] == delim)
126 ++p;
127 else if (p[1] == '\\')
128 *t++ = *p++;
129 *t++ = *p++;
133 * If the pattern string is empty, use the last RE (not just the
134 * last substitution RE).
136 if (*ptrn == '\0') {
137 if (sp->re == NULL) {
138 ex_emsg(sp, NULL, EXM_NOPREVRE);
139 return (1);
142 /* Re-compile the RE if necessary. */
143 if (!F_ISSET(sp, SC_RE_SEARCH) &&
144 re_compile(sp, sp->re, sp->re_len,
145 NULL, NULL, &sp->re_c, SEARCH_CSEARCH | SEARCH_MSG))
146 return (1);
147 flags = 0;
148 } else {
150 * !!!
151 * Compile the RE. Historic practice is that substitutes set
152 * the search direction as well as both substitute and search
153 * RE's. We compile the RE twice, as we don't want to bother
154 * ref counting the pattern string and (opaque) structure.
156 if (re_compile(sp, ptrn, t - ptrn, &sp->re,
157 &sp->re_len, &sp->re_c, SEARCH_CSEARCH | SEARCH_MSG))
158 return (1);
159 if (re_compile(sp, ptrn, t - ptrn, &sp->subre,
160 &sp->subre_len, &sp->subre_c, SEARCH_CSUBST | SEARCH_MSG))
161 return (1);
163 flags = SUB_FIRST;
164 sp->searchdir = FORWARD;
166 re = &sp->re_c;
169 * Get the replacement string.
171 * The special character & (\& if O_MAGIC not set) matches the
172 * entire RE. No handling of & is required here, it's done by
173 * re_sub().
175 * The special character ~ (\~ if O_MAGIC not set) inserts the
176 * previous replacement string into this replacement string.
177 * Count ~'s to figure out how much space we need. We could
178 * special case nonexistent last patterns or whether or not
179 * O_MAGIC is set, but it's probably not worth the effort.
181 * QUOTING NOTE:
183 * Only toss an escaping character if it escapes a delimiter or
184 * if O_MAGIC is set and it escapes a tilde.
186 * !!!
187 * If the entire replacement pattern is "%", then use the last
188 * replacement pattern. This semantic was added to vi in System
189 * V and then percolated elsewhere, presumably around the time
190 * that it was added to their version of ed(1).
192 if (p[0] == '\0' || p[0] == delim) {
193 if (p[0] == delim)
194 ++p;
195 if (sp->repl != NULL)
196 free(sp->repl);
197 sp->repl = NULL;
198 sp->repl_len = 0;
199 } else if (p[0] == '%' && (p[1] == '\0' || p[1] == delim))
200 p += p[1] == delim ? 2 : 1;
201 else {
202 for (rep = p, len = 0;
203 p[0] != '\0' && p[0] != delim; ++p, ++len)
204 if (p[0] == '~')
205 len += sp->repl_len;
206 GET_SPACE_RET(sp, bp, blen, len);
207 for (t = bp, len = 0, p = rep;;) {
208 if (p[0] == '\0' || p[0] == delim) {
209 if (p[0] == delim)
210 ++p;
211 break;
213 if (p[0] == '\\') {
214 if (p[1] == delim)
215 ++p;
216 else if (p[1] == '\\') {
217 *t++ = *p++;
218 ++len;
219 } else if (p[1] == '~') {
220 ++p;
221 if (!O_ISSET(sp, O_MAGIC))
222 goto tilde;
224 } else if (p[0] == '~' && O_ISSET(sp, O_MAGIC)) {
225 tilde: ++p;
226 memcpy(t, sp->repl, sp->repl_len);
227 t += sp->repl_len;
228 len += sp->repl_len;
229 continue;
231 *t++ = *p++;
232 ++len;
234 if ((sp->repl_len = len) != 0) {
235 if (sp->repl != NULL)
236 free(sp->repl);
237 if ((sp->repl = malloc(len)) == NULL) {
238 msgq(sp, M_SYSERR, NULL);
239 FREE_SPACE(sp, bp, blen);
240 return (1);
242 memcpy(sp->repl, bp, len);
244 FREE_SPACE(sp, bp, blen);
246 return (s(sp, cmdp, p, re, flags));
250 * ex_subagain --
251 * [line [,line]] & [cgr] [count] [#lp]]
253 * Substitute using the last substitute RE and replacement pattern.
255 * PUBLIC: int ex_subagain __P((SCR *, EXCMD *));
258 ex_subagain(sp, cmdp)
259 SCR *sp;
260 EXCMD *cmdp;
262 if (sp->subre == NULL) {
263 ex_emsg(sp, NULL, EXM_NOPREVRE);
264 return (1);
266 if (!F_ISSET(sp, SC_RE_SUBST) &&
267 re_compile(sp, sp->subre, sp->subre_len,
268 NULL, NULL, &sp->subre_c, SEARCH_CSUBST | SEARCH_MSG))
269 return (1);
270 return (s(sp,
271 cmdp, cmdp->argc ? cmdp->argv[0]->bp : NULL, &sp->subre_c, 0));
275 * ex_subtilde --
276 * [line [,line]] ~ [cgr] [count] [#lp]]
278 * Substitute using the last RE and last substitute replacement pattern.
280 * PUBLIC: int ex_subtilde __P((SCR *, EXCMD *));
283 ex_subtilde(sp, cmdp)
284 SCR *sp;
285 EXCMD *cmdp;
287 if (sp->re == NULL) {
288 ex_emsg(sp, NULL, EXM_NOPREVRE);
289 return (1);
291 if (!F_ISSET(sp, SC_RE_SEARCH) && re_compile(sp, sp->re,
292 sp->re_len, NULL, NULL, &sp->re_c, SEARCH_CSEARCH | SEARCH_MSG))
293 return (1);
294 return (s(sp,
295 cmdp, cmdp->argc ? cmdp->argv[0]->bp : NULL, &sp->re_c, 0));
299 * s --
300 * Do the substitution. This stuff is *really* tricky. There are lots of
301 * special cases, and general nastiness. Don't mess with it unless you're
302 * pretty confident.
304 * The nasty part of the substitution is what happens when the replacement
305 * string contains newlines. It's a bit tricky -- consider the information
306 * that has to be retained for "s/f\(o\)o/^M\1^M\1/". The solution here is
307 * to build a set of newline offsets which we use to break the line up later,
308 * when the replacement is done. Don't change it unless you're *damned*
309 * confident.
311 #define NEEDNEWLINE(sp) { \
312 if (sp->newl_len == sp->newl_cnt) { \
313 sp->newl_len += 25; \
314 REALLOC(sp, sp->newl, size_t *, \
315 sp->newl_len * sizeof(size_t)); \
316 if (sp->newl == NULL) { \
317 sp->newl_len = 0; \
318 return (1); \
323 #define BUILD(sp, l, len) { \
324 if (lbclen + (len) > lblen) { \
325 lblen += MAX(lbclen + (len), 256); \
326 REALLOC(sp, lb, char *, lblen); \
327 if (lb == NULL) { \
328 lbclen = 0; \
329 return (1); \
332 memcpy(lb + lbclen, l, len); \
333 lbclen += len; \
336 #define NEEDSP(sp, len, pnt) { \
337 if (lbclen + (len) > lblen) { \
338 lblen += MAX(lbclen + (len), 256); \
339 REALLOC(sp, lb, char *, lblen); \
340 if (lb == NULL) { \
341 lbclen = 0; \
342 return (1); \
344 pnt = lb + lbclen; \
348 static int
349 s(sp, cmdp, s, re, flags)
350 SCR *sp;
351 EXCMD *cmdp;
352 char *s;
353 regex_t *re;
354 u_int flags;
356 EVENT ev;
357 MARK from, to;
358 TEXTH tiq;
359 db_recno_t elno, lno, slno;
360 regmatch_t match[10];
361 size_t blen, cnt, last, lbclen, lblen, len, llen;
362 size_t offset, saved_offset, scno;
363 int cflag, lflag, nflag, pflag, rflag;
364 int didsub, do_eol_match, eflags, empty_ok, eval;
365 int linechanged, matched, quit, rval;
366 char *bp, *lb;
367 CHAR_T *p;
369 NEEDFILE(sp, cmdp);
371 slno = sp->lno;
372 scno = sp->cno;
375 * !!!
376 * Historically, the 'g' and 'c' suffices were always toggled as flags,
377 * so ":s/A/B/" was the same as ":s/A/B/ccgg". If O_EDCOMPATIBLE was
378 * not set, they were initialized to 0 for all substitute commands. If
379 * O_EDCOMPATIBLE was set, they were initialized to 0 only if the user
380 * specified substitute/replacement patterns (see ex_s()).
382 if (!O_ISSET(sp, O_EDCOMPATIBLE))
383 sp->c_suffix = sp->g_suffix = 0;
386 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
387 * it only displayed the last change. I'd disallow them, but they are
388 * useful in combination with the [v]global commands. In the current
389 * model the problem is combining them with the 'c' flag -- the screen
390 * would have to flip back and forth between the confirm screen and the
391 * ex print screen, which would be pretty awful. We do display all
392 * changes, though, for what that's worth.
394 * !!!
395 * Historic vi was fairly strict about the order of "options", the
396 * count, and "flags". I'm somewhat fuzzy on the difference between
397 * options and flags, anyway, so this is a simpler approach, and we
398 * just take it them in whatever order the user gives them. (The ex
399 * usage statement doesn't reflect this.)
401 cflag = lflag = nflag = pflag = rflag = 0;
402 if (s == NULL)
403 goto noargs;
404 for (lno = OOBLNO; *s != '\0'; ++s)
405 switch (*s) {
406 case ' ':
407 case '\t':
408 continue;
409 case '+':
410 ++cmdp->flagoff;
411 break;
412 case '-':
413 --cmdp->flagoff;
414 break;
415 case '0': case '1': case '2': case '3': case '4':
416 case '5': case '6': case '7': case '8': case '9':
417 if (lno != OOBLNO)
418 goto usage;
419 errno = 0;
420 lno = strtoul(s, &s, 10);
421 if (*s == '\0') /* Loop increment correction. */
422 --s;
423 if (errno == ERANGE) {
424 if (lno == LONG_MAX)
425 msgq(sp, M_ERR, "153|Count overflow");
426 else if (lno == LONG_MIN)
427 msgq(sp, M_ERR, "154|Count underflow");
428 else
429 msgq(sp, M_SYSERR, NULL);
430 return (1);
433 * In historic vi, the count was inclusive from the
434 * second address.
436 cmdp->addr1.lno = cmdp->addr2.lno;
437 cmdp->addr2.lno += lno - 1;
438 if (!db_exist(sp, cmdp->addr2.lno) &&
439 db_last(sp, &cmdp->addr2.lno))
440 return (1);
441 break;
442 case '#':
443 nflag = 1;
444 break;
445 case 'c':
446 sp->c_suffix = !sp->c_suffix;
448 /* Ex text structure initialization. */
449 if (F_ISSET(sp, SC_EX)) {
450 memset(&tiq, 0, sizeof(TEXTH));
451 CIRCLEQ_INIT(&tiq);
453 break;
454 case 'g':
455 sp->g_suffix = !sp->g_suffix;
456 break;
457 case 'l':
458 lflag = 1;
459 break;
460 case 'p':
461 pflag = 1;
462 break;
463 case 'r':
464 if (LF_ISSET(SUB_FIRST)) {
465 msgq(sp, M_ERR,
466 "155|Regular expression specified; r flag meaningless");
467 return (1);
469 if (!F_ISSET(sp, SC_RE_SEARCH)) {
470 ex_emsg(sp, NULL, EXM_NOPREVRE);
471 return (1);
473 rflag = 1;
474 re = &sp->re_c;
475 break;
476 default:
477 goto usage;
480 if (*s != '\0' || !rflag && LF_ISSET(SUB_MUSTSETR)) {
481 usage: ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE);
482 return (1);
485 noargs: if (F_ISSET(sp, SC_VI) && sp->c_suffix && (lflag || nflag || pflag)) {
486 msgq(sp, M_ERR,
487 "156|The #, l and p flags may not be combined with the c flag in vi mode");
488 return (1);
492 * bp: if interactive, line cache
493 * blen: if interactive, line cache length
494 * lb: build buffer pointer.
495 * lbclen: current length of built buffer.
496 * lblen; length of build buffer.
498 bp = lb = NULL;
499 blen = lbclen = lblen = 0;
501 /* For each line... */
502 lno = cmdp->addr1.lno == 0 ? 1 : cmdp->addr1.lno;
503 for (matched = quit = 0,
504 elno = cmdp->addr2.lno; !quit && lno <= elno; ++lno) {
506 /* Someone's unhappy, time to stop. */
507 if (INTERRUPTED(sp))
508 break;
510 /* Get the line. */
511 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
512 goto err;
515 * Make a local copy if doing confirmation -- when calling
516 * the confirm routine we're likely to lose the cached copy.
518 if (sp->c_suffix) {
519 if (bp == NULL) {
520 GET_SPACE_RET(sp, bp, blen, llen);
521 } else
522 ADD_SPACE_RET(sp, bp, blen, llen);
523 memcpy(bp, s, llen);
524 s = bp;
527 /* Start searching from the beginning. */
528 offset = 0;
529 len = llen;
531 /* Reset the build buffer offset. */
532 lbclen = 0;
534 /* Reset empty match flag. */
535 empty_ok = 1;
538 * We don't want to have to do a setline if the line didn't
539 * change -- keep track of whether or not this line changed.
540 * If doing confirmations, don't want to keep setting the
541 * line if change is refused -- keep track of substitutions.
543 didsub = linechanged = 0;
545 /* New line, do an EOL match. */
546 do_eol_match = 1;
548 /* It's not nul terminated, but we pretend it is. */
549 eflags = REG_STARTEND;
552 * The search area is from s + offset to the EOL.
554 * Generally, match[0].rm_so is the offset of the start
555 * of the match from the start of the search, and offset
556 * is the offset of the start of the last search.
558 nextmatch: match[0].rm_so = 0;
559 match[0].rm_eo = len;
561 /* Get the next match. */
562 eval = regexec(re, (char *)s + offset, 10, match, eflags);
565 * There wasn't a match or if there was an error, deal with
566 * it. If there was a previous match in this line, resolve
567 * the changes into the database. Otherwise, just move on.
569 if (eval == REG_NOMATCH)
570 goto endmatch;
571 if (eval != 0) {
572 re_error(sp, eval, re);
573 goto err;
575 matched = 1;
577 /* Only the first search can match an anchored expression. */
578 eflags |= REG_NOTBOL;
581 * !!!
582 * It's possible to match 0-length strings -- for example, the
583 * command s;a*;X;, when matched against the string "aabb" will
584 * result in "XbXbX", i.e. the matches are "aa", the space
585 * between the b's and the space between the b's and the end of
586 * the string. There is a similar space between the beginning
587 * of the string and the a's. The rule that we use (because vi
588 * historically used it) is that any 0-length match, occurring
589 * immediately after a match, is ignored. Otherwise, the above
590 * example would have resulted in "XXbXbX". Another example is
591 * incorrectly using " *" to replace groups of spaces with one
592 * space.
594 * The way we do this is that if we just had a successful match,
595 * the starting offset does not skip characters, and the match
596 * is empty, ignore the match and move forward. If there's no
597 * more characters in the string, we were attempting to match
598 * after the last character, so quit.
600 if (!empty_ok && match[0].rm_so == 0 && match[0].rm_eo == 0) {
601 empty_ok = 1;
602 if (len == 0)
603 goto endmatch;
604 BUILD(sp, s + offset, 1)
605 ++offset;
606 --len;
607 goto nextmatch;
610 /* Confirm change. */
611 if (sp->c_suffix) {
613 * Set the cursor position for confirmation. Note,
614 * if we matched on a '$', the cursor may be past
615 * the end of line.
617 from.lno = to.lno = lno;
618 from.cno = match[0].rm_so + offset;
619 to.cno = match[0].rm_eo + offset;
621 * Both ex and vi have to correct for a change before
622 * the first character in the line.
624 if (llen == 0)
625 from.cno = to.cno = 0;
626 if (F_ISSET(sp, SC_VI)) {
628 * Only vi has to correct for a change after
629 * the last character in the line.
631 * XXX
632 * It would be nice to change the vi code so
633 * that we could display a cursor past EOL.
635 if (to.cno >= llen)
636 to.cno = llen - 1;
637 if (from.cno >= llen)
638 from.cno = llen - 1;
640 sp->lno = from.lno;
641 sp->cno = from.cno;
642 if (vs_refresh(sp, 1))
643 goto err;
645 vs_update(sp, msg_cat(sp,
646 "169|Confirm change? [n]", NULL), NULL);
648 if (v_event_get(sp, &ev, 0, 0))
649 goto err;
650 switch (ev.e_event) {
651 case E_CHARACTER:
652 break;
653 case E_EOF:
654 case E_ERR:
655 case E_INTERRUPT:
656 goto lquit;
657 default:
658 v_event_err(sp, &ev);
659 goto lquit;
661 } else {
662 if (ex_print(sp, cmdp, &from, &to, 0) ||
663 ex_scprint(sp, &from, &to))
664 goto lquit;
665 if (ex_txt(sp, &tiq, 0, TXT_CR))
666 goto err;
667 ev.e_c = tiq.cqh_first->lb[0];
670 switch (ev.e_c) {
671 case CH_YES:
672 break;
673 default:
674 case CH_NO:
675 didsub = 0;
676 BUILD(sp, s +offset, match[0].rm_eo);
677 goto skip;
678 case CH_QUIT:
679 /* Set the quit/interrupted flags. */
680 lquit: quit = 1;
681 F_SET(sp->gp, G_INTERRUPTED);
684 * Resolve any changes, then return to (and
685 * exit from) the main loop.
687 goto endmatch;
692 * Set the cursor to the last position changed, converting
693 * from 1-based to 0-based.
695 sp->lno = lno;
696 sp->cno = match[0].rm_so;
698 /* Copy the bytes before the match into the build buffer. */
699 BUILD(sp, s + offset, match[0].rm_so);
701 /* Substitute the matching bytes. */
702 didsub = 1;
703 if (re_sub(sp, s + offset, &lb, &lbclen, &lblen, match))
704 goto err;
706 /* Set the change flag so we know this line was modified. */
707 linechanged = 1;
709 /* Move past the matched bytes. */
710 skip: offset += match[0].rm_eo;
711 len -= match[0].rm_eo;
713 /* A match cannot be followed by an empty pattern. */
714 empty_ok = 0;
717 * If doing a global change with confirmation, we have to
718 * update the screen. The basic idea is to store the line
719 * so the screen update routines can find it, and restart.
721 if (didsub && sp->c_suffix && sp->g_suffix) {
723 * The new search offset will be the end of the
724 * modified line.
726 saved_offset = lbclen;
728 /* Copy the rest of the line. */
729 if (len)
730 BUILD(sp, s + offset, len)
732 /* Set the new offset. */
733 offset = saved_offset;
735 /* Store inserted lines, adjusting the build buffer. */
736 last = 0;
737 if (sp->newl_cnt) {
738 for (cnt = 0;
739 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
740 if (db_insert(sp, lno,
741 lb + last, sp->newl[cnt] - last))
742 goto err;
743 last = sp->newl[cnt] + 1;
744 ++sp->rptlines[L_ADDED];
746 lbclen -= last;
747 offset -= last;
748 sp->newl_cnt = 0;
751 /* Store and retrieve the line. */
752 if (db_set(sp, lno, lb + last, lbclen))
753 goto err;
754 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
755 goto err;
756 ADD_SPACE_RET(sp, bp, blen, llen)
757 memcpy(bp, s, llen);
758 s = bp;
759 len = llen - offset;
761 /* Restart the build. */
762 lbclen = 0;
763 BUILD(sp, s, offset);
766 * If we haven't already done the after-the-string
767 * match, do one. Set REG_NOTEOL so the '$' pattern
768 * only matches once.
770 if (!do_eol_match)
771 goto endmatch;
772 if (offset == len) {
773 do_eol_match = 0;
774 eflags |= REG_NOTEOL;
776 goto nextmatch;
780 * If it's a global:
782 * If at the end of the string, do a test for the after
783 * the string match. Set REG_NOTEOL so the '$' pattern
784 * only matches once.
786 if (sp->g_suffix && do_eol_match) {
787 if (len == 0) {
788 do_eol_match = 0;
789 eflags |= REG_NOTEOL;
791 goto nextmatch;
794 endmatch: if (!linechanged)
795 continue;
797 /* Copy any remaining bytes into the build buffer. */
798 if (len)
799 BUILD(sp, s + offset, len)
801 /* Store inserted lines, adjusting the build buffer. */
802 last = 0;
803 if (sp->newl_cnt) {
804 for (cnt = 0;
805 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
806 if (db_insert(sp,
807 lno, lb + last, sp->newl[cnt] - last))
808 goto err;
809 last = sp->newl[cnt] + 1;
810 ++sp->rptlines[L_ADDED];
812 lbclen -= last;
813 sp->newl_cnt = 0;
816 /* Store the changed line. */
817 if (db_set(sp, lno, lb + last, lbclen))
818 goto err;
820 /* Update changed line counter. */
821 if (sp->rptlchange != lno) {
822 sp->rptlchange = lno;
823 ++sp->rptlines[L_CHANGED];
827 * !!!
828 * Display as necessary. Historic practice is to only
829 * display the last line of a line split into multiple
830 * lines.
832 if (lflag || nflag || pflag) {
833 from.lno = to.lno = lno;
834 from.cno = to.cno = 0;
835 if (lflag)
836 (void)ex_print(sp, cmdp, &from, &to, E_C_LIST);
837 if (nflag)
838 (void)ex_print(sp, cmdp, &from, &to, E_C_HASH);
839 if (pflag)
840 (void)ex_print(sp, cmdp, &from, &to, E_C_PRINT);
845 * !!!
846 * Historically, vi attempted to leave the cursor at the same place if
847 * the substitution was done at the current cursor position. Otherwise
848 * it moved it to the first non-blank of the last line changed. There
849 * were some problems: for example, :s/$/foo/ with the cursor on the
850 * last character of the line left the cursor on the last character, or
851 * the & command with multiple occurrences of the matching string in the
852 * line usually left the cursor in a fairly random position.
854 * We try to do the same thing, with the exception that if the user is
855 * doing substitution with confirmation, we move to the last line about
856 * which the user was consulted, as opposed to the last line that they
857 * actually changed. This prevents a screen flash if the user doesn't
858 * change many of the possible lines.
860 if (!sp->c_suffix && (sp->lno != slno || sp->cno != scno)) {
861 sp->cno = 0;
862 (void)nonblank(sp, sp->lno, &sp->cno);
866 * If not in a global command, and nothing matched, say so.
867 * Else, if none of the lines displayed, put something up.
869 rval = 0;
870 if (!matched) {
871 if (!F_ISSET(sp, SC_EX_GLOBAL)) {
872 msgq(sp, M_ERR, "157|No match found");
873 goto err;
875 } else if (!lflag && !nflag && !pflag)
876 F_SET(cmdp, E_AUTOPRINT);
878 if (0) {
879 err: rval = 1;
882 if (bp != NULL)
883 FREE_SPACE(sp, bp, blen);
884 if (lb != NULL)
885 free(lb);
886 return (rval);
890 * re_compile --
891 * Compile the RE.
893 * PUBLIC: int re_compile __P((SCR *,
894 * PUBLIC: char *, size_t, char **, size_t *, regex_t *, u_int));
897 re_compile(sp, ptrn, plen, ptrnp, lenp, rep, flags)
898 SCR *sp;
899 char *ptrn, **ptrnp;
900 size_t plen, *lenp;
901 regex_t *rep;
902 u_int flags;
904 size_t len;
905 int reflags, replaced, rval;
906 char *p;
908 /* Set RE flags. */
909 reflags = 0;
910 if (LF_ISSET(SEARCH_EXTEND))
911 reflags |= REG_EXTENDED;
912 if (LF_ISSET(SEARCH_IC))
913 reflags |= REG_ICASE;
914 if (LF_ISSET(SEARCH_LITERAL))
915 reflags |= REG_NOSPEC;
916 if (!LF_ISSET(SEARCH_NOOPT | SEARCH_CSCOPE | SEARCH_TAG)) {
917 if (O_ISSET(sp, O_EXTENDED))
918 reflags |= REG_EXTENDED;
919 if (O_ISSET(sp, O_IGNORECASE))
920 reflags |= REG_ICASE;
921 if (O_ISSET(sp, O_ICLOWER))
922 goto iclower;
924 if (LF_ISSET(SEARCH_ICL)) {
925 iclower: for (p = ptrn, len = plen; len > 0; ++p, --len)
926 if (isupper(*p))
927 break;
928 if (len == 0)
929 reflags |= REG_ICASE;
932 /* If we're replacing a saved value, clear the old one. */
933 if (LF_ISSET(SEARCH_CSEARCH) && F_ISSET(sp, SC_RE_SEARCH)) {
934 regfree(&sp->re_c);
935 F_CLR(sp, SC_RE_SEARCH);
937 if (LF_ISSET(SEARCH_CSUBST) && F_ISSET(sp, SC_RE_SUBST)) {
938 regfree(&sp->subre_c);
939 F_CLR(sp, SC_RE_SUBST);
943 * If we're saving the string, it's a pattern we haven't seen before,
944 * so convert the vi-style RE's to POSIX 1003.2 RE's. Save a copy for
945 * later recompilation. Free any previously saved value.
947 if (ptrnp != NULL) {
948 replaced = 0;
949 if (LF_ISSET(SEARCH_CSCOPE)) {
950 if (re_cscope_conv(sp, &ptrn, &plen, &replaced))
951 return (1);
953 * XXX
954 * Currently, the match-any-<blank> expression used in
955 * re_cscope_conv() requires extended RE's. This may
956 * not be right or safe.
958 reflags |= REG_EXTENDED;
959 } else if (LF_ISSET(SEARCH_TAG)) {
960 if (re_tag_conv(sp, &ptrn, &plen, &replaced))
961 return (1);
962 } else if (!LF_ISSET(SEARCH_LITERAL))
963 if (re_conv(sp, &ptrn, &plen, &replaced))
964 return (1);
966 /* Discard previous pattern. */
967 if (*ptrnp != NULL) {
968 free(*ptrnp);
969 *ptrnp = NULL;
971 if (lenp != NULL)
972 *lenp = plen;
975 * Copy the string into allocated memory.
977 * XXX
978 * Regcomp isn't 8-bit clean, so the pattern is nul-terminated
979 * for now. There's just no other solution.
981 MALLOC(sp, *ptrnp, char *, plen + 1);
982 if (*ptrnp != NULL) {
983 memcpy(*ptrnp, ptrn, plen);
984 (*ptrnp)[plen] = '\0';
987 /* Free up conversion-routine-allocated memory. */
988 if (replaced)
989 FREE_SPACE(sp, ptrn, 0);
991 if (*ptrnp == NULL)
992 return (1);
994 ptrn = *ptrnp;
998 * XXX
999 * Regcomp isn't 8-bit clean, so we just lost if the pattern
1000 * contained a nul. Bummer!
1002 if ((rval = regcomp(rep, ptrn, /* plen, */ reflags)) != 0) {
1003 if (LF_ISSET(SEARCH_MSG))
1004 re_error(sp, rval, rep);
1005 return (1);
1008 if (LF_ISSET(SEARCH_CSEARCH))
1009 F_SET(sp, SC_RE_SEARCH);
1010 if (LF_ISSET(SEARCH_CSUBST))
1011 F_SET(sp, SC_RE_SUBST);
1013 return (0);
1017 * re_conv --
1018 * Convert vi's regular expressions into something that the
1019 * the POSIX 1003.2 RE functions can handle.
1021 * There are three conversions we make to make vi's RE's (specifically
1022 * the global, search, and substitute patterns) work with POSIX RE's.
1024 * 1: If O_MAGIC is not set, strip backslashes from the magic character
1025 * set (.[*~) that have them, and add them to the ones that don't.
1026 * 2: If O_MAGIC is not set, the string "\~" is replaced with the text
1027 * from the last substitute command's replacement string. If O_MAGIC
1028 * is set, it's the string "~".
1029 * 3: The pattern \<ptrn\> does "word" searches, convert it to use the
1030 * new RE escapes.
1032 * !!!/XXX
1033 * This doesn't exactly match the historic behavior of vi because we do
1034 * the ~ substitution before calling the RE engine, so magic characters
1035 * in the replacement string will be expanded by the RE engine, and they
1036 * weren't historically. It's a bug.
1038 static int
1039 re_conv(sp, ptrnp, plenp, replacedp)
1040 SCR *sp;
1041 char **ptrnp;
1042 size_t *plenp;
1043 int *replacedp;
1045 size_t blen, len, needlen;
1046 int magic;
1047 char *bp, *p, *t;
1050 * First pass through, we figure out how much space we'll need.
1051 * We do it in two passes, on the grounds that most of the time
1052 * the user is doing a search and won't have magic characters.
1053 * That way we can skip most of the memory allocation and copies.
1055 magic = 0;
1056 for (p = *ptrnp, len = *plenp, needlen = 0; len > 0; ++p, --len)
1057 switch (*p) {
1058 case '\\':
1059 if (len > 1) {
1060 --len;
1061 switch (*++p) {
1062 case '<':
1063 magic = 1;
1064 needlen += sizeof(RE_WSTART);
1065 break;
1066 case '>':
1067 magic = 1;
1068 needlen += sizeof(RE_WSTOP);
1069 break;
1070 case '~':
1071 if (!O_ISSET(sp, O_MAGIC)) {
1072 magic = 1;
1073 needlen += sp->repl_len;
1075 break;
1076 case '.':
1077 case '[':
1078 case '*':
1079 if (!O_ISSET(sp, O_MAGIC)) {
1080 magic = 1;
1081 needlen += 1;
1083 break;
1084 default:
1085 needlen += 2;
1087 } else
1088 needlen += 1;
1089 break;
1090 case '~':
1091 if (O_ISSET(sp, O_MAGIC)) {
1092 magic = 1;
1093 needlen += sp->repl_len;
1095 break;
1096 case '.':
1097 case '[':
1098 case '*':
1099 if (!O_ISSET(sp, O_MAGIC)) {
1100 magic = 1;
1101 needlen += 2;
1103 break;
1104 default:
1105 needlen += 1;
1106 break;
1109 if (!magic) {
1110 *replacedp = 0;
1111 return (0);
1114 /* Get enough memory to hold the final pattern. */
1115 *replacedp = 1;
1116 GET_SPACE_RET(sp, bp, blen, needlen);
1118 for (p = *ptrnp, len = *plenp, t = bp; len > 0; ++p, --len)
1119 switch (*p) {
1120 case '\\':
1121 if (len > 1) {
1122 --len;
1123 switch (*++p) {
1124 case '<':
1125 memcpy(t,
1126 RE_WSTART, sizeof(RE_WSTART) - 1);
1127 t += sizeof(RE_WSTART) - 1;
1128 break;
1129 case '>':
1130 memcpy(t,
1131 RE_WSTOP, sizeof(RE_WSTOP) - 1);
1132 t += sizeof(RE_WSTOP) - 1;
1133 break;
1134 case '~':
1135 if (O_ISSET(sp, O_MAGIC))
1136 *t++ = '~';
1137 else {
1138 memcpy(t,
1139 sp->repl, sp->repl_len);
1140 t += sp->repl_len;
1142 break;
1143 case '.':
1144 case '[':
1145 case '*':
1146 if (O_ISSET(sp, O_MAGIC))
1147 *t++ = '\\';
1148 *t++ = *p;
1149 break;
1150 default:
1151 *t++ = '\\';
1152 *t++ = *p;
1154 } else
1155 *t++ = '\\';
1156 break;
1157 case '~':
1158 if (O_ISSET(sp, O_MAGIC)) {
1159 memcpy(t, sp->repl, sp->repl_len);
1160 t += sp->repl_len;
1161 } else
1162 *t++ = '~';
1163 break;
1164 case '.':
1165 case '[':
1166 case '*':
1167 if (!O_ISSET(sp, O_MAGIC))
1168 *t++ = '\\';
1169 *t++ = *p;
1170 break;
1171 default:
1172 *t++ = *p;
1173 break;
1176 *ptrnp = bp;
1177 *plenp = t - bp;
1178 return (0);
1182 * re_tag_conv --
1183 * Convert a tags search path into something that the POSIX
1184 * 1003.2 RE functions can handle.
1186 static int
1187 re_tag_conv(sp, ptrnp, plenp, replacedp)
1188 SCR *sp;
1189 char **ptrnp;
1190 size_t *plenp;
1191 int *replacedp;
1193 size_t blen, len;
1194 int lastdollar;
1195 char *bp, *p, *t;
1197 len = *plenp;
1199 /* Max memory usage is 2 times the length of the string. */
1200 *replacedp = 1;
1201 GET_SPACE_RET(sp, bp, blen, len * 2);
1203 p = *ptrnp;
1204 t = bp;
1206 /* If the last character is a '/' or '?', we just strip it. */
1207 if (len > 0 && (p[len - 1] == '/' || p[len - 1] == '?'))
1208 --len;
1210 /* If the next-to-last or last character is a '$', it's magic. */
1211 if (len > 0 && p[len - 1] == '$') {
1212 --len;
1213 lastdollar = 1;
1214 } else
1215 lastdollar = 0;
1217 /* If the first character is a '/' or '?', we just strip it. */
1218 if (len > 0 && (p[0] == '/' || p[0] == '?')) {
1219 ++p;
1220 --len;
1223 /* If the first or second character is a '^', it's magic. */
1224 if (p[0] == '^') {
1225 *t++ = *p++;
1226 --len;
1230 * Escape every other magic character we can find, meanwhile stripping
1231 * the backslashes ctags inserts when escaping the search delimiter
1232 * characters.
1234 for (; len > 0; --len) {
1235 if (p[0] == '\\' && (p[1] == '/' || p[1] == '?')) {
1236 ++p;
1237 --len;
1238 } else if (strchr("^.[]$*", p[0]))
1239 *t++ = '\\';
1240 *t++ = *p++;
1242 if (lastdollar)
1243 *t++ = '$';
1245 *ptrnp = bp;
1246 *plenp = t - bp;
1247 return (0);
1251 * re_cscope_conv --
1252 * Convert a cscope search path into something that the POSIX
1253 * 1003.2 RE functions can handle.
1255 static int
1256 re_cscope_conv(sp, ptrnp, plenp, replacedp)
1257 SCR *sp;
1258 char **ptrnp;
1259 size_t *plenp;
1260 int *replacedp;
1262 size_t blen, len, nspaces;
1263 char *bp, *p, *t;
1266 * Each space in the source line printed by cscope represents an
1267 * arbitrary sequence of spaces, tabs, and comments.
1269 #define CSCOPE_RE_SPACE "([ \t]|/\\*([^*]|\\*/)*\\*/)*"
1270 for (nspaces = 0, p = *ptrnp, len = *plenp; len > 0; ++p, --len)
1271 if (*p == ' ')
1272 ++nspaces;
1275 * Allocate plenty of space:
1276 * the string, plus potential escaping characters;
1277 * nspaces + 2 copies of CSCOPE_RE_SPACE;
1278 * ^, $, nul terminator characters.
1280 *replacedp = 1;
1281 len = (p - *ptrnp) * 2 + (nspaces + 2) * sizeof(CSCOPE_RE_SPACE) + 3;
1282 GET_SPACE_RET(sp, bp, blen, len);
1284 p = *ptrnp;
1285 t = bp;
1287 *t++ = '^';
1288 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1289 t += sizeof(CSCOPE_RE_SPACE) - 1;
1291 for (len = *plenp; len > 0; ++p, --len)
1292 if (*p == ' ') {
1293 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1294 t += sizeof(CSCOPE_RE_SPACE) - 1;
1295 } else {
1296 if (strchr("\\^.[]$*+?()|{}", *p))
1297 *t++ = '\\';
1298 *t++ = *p;
1301 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1302 t += sizeof(CSCOPE_RE_SPACE) - 1;
1303 *t++ = '$';
1305 *ptrnp = bp;
1306 *plenp = t - bp;
1307 return (0);
1311 * re_error --
1312 * Report a regular expression error.
1314 * PUBLIC: void re_error __P((SCR *, int, regex_t *));
1316 void
1317 re_error(sp, errcode, preg)
1318 SCR *sp;
1319 int errcode;
1320 regex_t *preg;
1322 size_t s;
1323 char *oe;
1325 s = regerror(errcode, preg, "", 0);
1326 if ((oe = malloc(s)) == NULL)
1327 msgq(sp, M_SYSERR, NULL);
1328 else {
1329 (void)regerror(errcode, preg, oe, s);
1330 msgq(sp, M_ERR, "RE error: %s", oe);
1331 free(oe);
1336 * re_sub --
1337 * Do the substitution for a regular expression.
1339 static int
1340 re_sub(sp, ip, lbp, lbclenp, lblenp, match)
1341 SCR *sp;
1342 char *ip; /* Input line. */
1343 char **lbp;
1344 size_t *lbclenp, *lblenp;
1345 regmatch_t match[10];
1347 enum { C_NOTSET, C_LOWER, C_ONELOWER, C_ONEUPPER, C_UPPER } conv;
1348 size_t lbclen, lblen; /* Local copies. */
1349 size_t mlen; /* Match length. */
1350 size_t rpl; /* Remaining replacement length. */
1351 char *rp; /* Replacement pointer. */
1352 int ch;
1353 int no; /* Match replacement offset. */
1354 char *p, *t; /* Buffer pointers. */
1355 char *lb; /* Local copies. */
1357 lb = *lbp; /* Get local copies. */
1358 lbclen = *lbclenp;
1359 lblen = *lblenp;
1362 * QUOTING NOTE:
1364 * There are some special sequences that vi provides in the
1365 * replacement patterns.
1366 * & string the RE matched (\& if nomagic set)
1367 * \# n-th regular subexpression
1368 * \E end \U, \L conversion
1369 * \e end \U, \L conversion
1370 * \l convert the next character to lower-case
1371 * \L convert to lower-case, until \E, \e, or end of replacement
1372 * \u convert the next character to upper-case
1373 * \U convert to upper-case, until \E, \e, or end of replacement
1375 * Otherwise, since this is the lowest level of replacement, discard
1376 * all escaping characters. This (hopefully) matches historic practice.
1378 #define OUTCH(ch, nltrans) { \
1379 CHAR_T __ch = (ch); \
1380 u_int __value = KEY_VAL(sp, __ch); \
1381 if (nltrans && (__value == K_CR || __value == K_NL)) { \
1382 NEEDNEWLINE(sp); \
1383 sp->newl[sp->newl_cnt++] = lbclen; \
1384 } else if (conv != C_NOTSET) { \
1385 switch (conv) { \
1386 case C_ONELOWER: \
1387 conv = C_NOTSET; \
1388 /* FALLTHROUGH */ \
1389 case C_LOWER: \
1390 if (isupper(__ch)) \
1391 __ch = tolower(__ch); \
1392 break; \
1393 case C_ONEUPPER: \
1394 conv = C_NOTSET; \
1395 /* FALLTHROUGH */ \
1396 case C_UPPER: \
1397 if (islower(__ch)) \
1398 __ch = toupper(__ch); \
1399 break; \
1400 default: \
1401 abort(); \
1404 NEEDSP(sp, 1, p); \
1405 *p++ = __ch; \
1406 ++lbclen; \
1408 conv = C_NOTSET;
1409 for (rp = sp->repl, rpl = sp->repl_len, p = lb + lbclen; rpl--;) {
1410 switch (ch = *rp++) {
1411 case '&':
1412 if (O_ISSET(sp, O_MAGIC)) {
1413 no = 0;
1414 goto subzero;
1416 break;
1417 case '\\':
1418 if (rpl == 0)
1419 break;
1420 --rpl;
1421 switch (ch = *rp) {
1422 case '&':
1423 ++rp;
1424 if (!O_ISSET(sp, O_MAGIC)) {
1425 no = 0;
1426 goto subzero;
1428 break;
1429 case '0': case '1': case '2': case '3': case '4':
1430 case '5': case '6': case '7': case '8': case '9':
1431 no = *rp++ - '0';
1432 subzero: if (match[no].rm_so == -1 ||
1433 match[no].rm_eo == -1)
1434 break;
1435 mlen = match[no].rm_eo - match[no].rm_so;
1436 for (t = ip + match[no].rm_so; mlen--; ++t)
1437 OUTCH(*t, 0);
1438 continue;
1439 case 'e':
1440 case 'E':
1441 ++rp;
1442 conv = C_NOTSET;
1443 continue;
1444 case 'l':
1445 ++rp;
1446 conv = C_ONELOWER;
1447 continue;
1448 case 'L':
1449 ++rp;
1450 conv = C_LOWER;
1451 continue;
1452 case 'u':
1453 ++rp;
1454 conv = C_ONEUPPER;
1455 continue;
1456 case 'U':
1457 ++rp;
1458 conv = C_UPPER;
1459 continue;
1460 default:
1461 ++rp;
1462 break;
1465 OUTCH(ch, 1);
1468 *lbp = lb; /* Update caller's information. */
1469 *lbclenp = lbclen;
1470 *lblenp = lblen;
1471 return (0);