I've added a 'description' field.
[nvi.git] / ex / ex_subst.c
blob48c8dc37be2a3bf8cdebd8bcbbda6c1f654cbdbd
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.39 1996/12/16 09:40:10 bostic Exp $ (Berkeley) $Date: 1996/12/16 09:40:10 $";
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 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;
368 NEEDFILE(sp, cmdp);
370 slno = sp->lno;
371 scno = sp->cno;
374 * !!!
375 * Historically, the 'g' and 'c' suffices were always toggled as flags,
376 * so ":s/A/B/" was the same as ":s/A/B/ccgg". If O_EDCOMPATIBLE was
377 * not set, they were initialized to 0 for all substitute commands. If
378 * O_EDCOMPATIBLE was set, they were initialized to 0 only if the user
379 * specified substitute/replacement patterns (see ex_s()).
381 if (!O_ISSET(sp, O_EDCOMPATIBLE))
382 sp->c_suffix = sp->g_suffix = 0;
385 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
386 * it only displayed the last change. I'd disallow them, but they are
387 * useful in combination with the [v]global commands. In the current
388 * model the problem is combining them with the 'c' flag -- the screen
389 * would have to flip back and forth between the confirm screen and the
390 * ex print screen, which would be pretty awful. We do display all
391 * changes, though, for what that's worth.
393 * !!!
394 * Historic vi was fairly strict about the order of "options", the
395 * count, and "flags". I'm somewhat fuzzy on the difference between
396 * options and flags, anyway, so this is a simpler approach, and we
397 * just take it them in whatever order the user gives them. (The ex
398 * usage statement doesn't reflect this.)
400 cflag = lflag = nflag = pflag = rflag = 0;
401 if (s == NULL)
402 goto noargs;
403 for (lno = OOBLNO; *s != '\0'; ++s)
404 switch (*s) {
405 case ' ':
406 case '\t':
407 continue;
408 case '+':
409 ++cmdp->flagoff;
410 break;
411 case '-':
412 --cmdp->flagoff;
413 break;
414 case '0': case '1': case '2': case '3': case '4':
415 case '5': case '6': case '7': case '8': case '9':
416 if (lno != OOBLNO)
417 goto usage;
418 errno = 0;
419 lno = strtoul(s, &s, 10);
420 if (*s == '\0') /* Loop increment correction. */
421 --s;
422 if (errno == ERANGE) {
423 if (lno == LONG_MAX)
424 msgq(sp, M_ERR, "153|Count overflow");
425 else if (lno == LONG_MIN)
426 msgq(sp, M_ERR, "154|Count underflow");
427 else
428 msgq(sp, M_SYSERR, NULL);
429 return (1);
432 * In historic vi, the count was inclusive from the
433 * second address.
435 cmdp->addr1.lno = cmdp->addr2.lno;
436 cmdp->addr2.lno += lno - 1;
437 if (!db_exist(sp, cmdp->addr2.lno) &&
438 db_last(sp, &cmdp->addr2.lno))
439 return (1);
440 break;
441 case '#':
442 nflag = 1;
443 break;
444 case 'c':
445 sp->c_suffix = !sp->c_suffix;
447 /* Ex text structure initialization. */
448 if (F_ISSET(sp, SC_EX)) {
449 memset(&tiq, 0, sizeof(TEXTH));
450 CIRCLEQ_INIT(&tiq);
452 break;
453 case 'g':
454 sp->g_suffix = !sp->g_suffix;
455 break;
456 case 'l':
457 lflag = 1;
458 break;
459 case 'p':
460 pflag = 1;
461 break;
462 case 'r':
463 if (LF_ISSET(SUB_FIRST)) {
464 msgq(sp, M_ERR,
465 "155|Regular expression specified; r flag meaningless");
466 return (1);
468 if (!F_ISSET(sp, SC_RE_SEARCH)) {
469 ex_emsg(sp, NULL, EXM_NOPREVRE);
470 return (1);
472 rflag = 1;
473 re = &sp->re_c;
474 break;
475 default:
476 goto usage;
479 if (*s != '\0' || !rflag && LF_ISSET(SUB_MUSTSETR)) {
480 usage: ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE);
481 return (1);
484 noargs: if (F_ISSET(sp, SC_VI) && sp->c_suffix && (lflag || nflag || pflag)) {
485 msgq(sp, M_ERR,
486 "156|The #, l and p flags may not be combined with the c flag in vi mode");
487 return (1);
491 * bp: if interactive, line cache
492 * blen: if interactive, line cache length
493 * lb: build buffer pointer.
494 * lbclen: current length of built buffer.
495 * lblen; length of build buffer.
497 bp = lb = NULL;
498 blen = lbclen = lblen = 0;
500 /* For each line... */
501 for (matched = quit = 0, lno = cmdp->addr1.lno,
502 elno = cmdp->addr2.lno; !quit && lno <= elno; ++lno) {
504 /* Someone's unhappy, time to stop. */
505 if (INTERRUPTED(sp))
506 break;
508 /* Get the line. */
509 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
510 goto err;
513 * Make a local copy if doing confirmation -- when calling
514 * the confirm routine we're likely to lose the cached copy.
516 if (sp->c_suffix) {
517 if (bp == NULL) {
518 GET_SPACE_RET(sp, bp, blen, llen);
519 } else
520 ADD_SPACE_RET(sp, bp, blen, llen);
521 memcpy(bp, s, llen);
522 s = bp;
525 /* Start searching from the beginning. */
526 offset = 0;
527 len = llen;
529 /* Reset the build buffer offset. */
530 lbclen = 0;
532 /* Reset empty match flag. */
533 empty_ok = 1;
536 * We don't want to have to do a setline if the line didn't
537 * change -- keep track of whether or not this line changed.
538 * If doing confirmations, don't want to keep setting the
539 * line if change is refused -- keep track of substitutions.
541 didsub = linechanged = 0;
543 /* New line, do an EOL match. */
544 do_eol_match = 1;
546 /* It's not nul terminated, but we pretend it is. */
547 eflags = REG_STARTEND;
550 * The search area is from s + offset to the EOL.
552 * Generally, match[0].rm_so is the offset of the start
553 * of the match from the start of the search, and offset
554 * is the offset of the start of the last search.
556 nextmatch: match[0].rm_so = 0;
557 match[0].rm_eo = len;
559 /* Get the next match. */
560 eval = regexec(re, (char *)s + offset, 10, match, eflags);
563 * There wasn't a match or if there was an error, deal with
564 * it. If there was a previous match in this line, resolve
565 * the changes into the database. Otherwise, just move on.
567 if (eval == REG_NOMATCH)
568 goto endmatch;
569 if (eval != 0) {
570 re_error(sp, eval, re);
571 goto err;
573 matched = 1;
575 /* Only the first search can match an anchored expression. */
576 eflags |= REG_NOTBOL;
579 * !!!
580 * It's possible to match 0-length strings -- for example, the
581 * command s;a*;X;, when matched against the string "aabb" will
582 * result in "XbXbX", i.e. the matches are "aa", the space
583 * between the b's and the space between the b's and the end of
584 * the string. There is a similar space between the beginning
585 * of the string and the a's. The rule that we use (because vi
586 * historically used it) is that any 0-length match, occurring
587 * immediately after a match, is ignored. Otherwise, the above
588 * example would have resulted in "XXbXbX". Another example is
589 * incorrectly using " *" to replace groups of spaces with one
590 * space.
592 * The way we do this is that if we just had a successful match,
593 * the starting offset does not skip characters, and the match
594 * is empty, ignore the match and move forward. If there's no
595 * more characters in the string, we were attempting to match
596 * after the last character, so quit.
598 if (!empty_ok && match[0].rm_so == 0 && match[0].rm_eo == 0) {
599 empty_ok = 1;
600 if (len == 0)
601 goto endmatch;
602 BUILD(sp, s + offset, 1)
603 ++offset;
604 --len;
605 goto nextmatch;
608 /* Confirm change. */
609 if (sp->c_suffix) {
611 * Set the cursor position for confirmation. Note,
612 * if we matched on a '$', the cursor may be past
613 * the end of line.
615 from.lno = to.lno = lno;
616 from.cno = match[0].rm_so + offset;
617 to.cno = match[0].rm_eo + offset;
619 * Both ex and vi have to correct for a change before
620 * the first character in the line.
622 if (llen == 0)
623 from.cno = to.cno = 0;
624 if (F_ISSET(sp, SC_VI)) {
626 * Only vi has to correct for a change after
627 * the last character in the line.
629 * XXX
630 * It would be nice to change the vi code so
631 * that we could display a cursor past EOL.
633 if (to.cno >= llen)
634 to.cno = llen - 1;
635 if (from.cno >= llen)
636 from.cno = llen - 1;
638 sp->lno = from.lno;
639 sp->cno = from.cno;
640 if (vs_refresh(sp, 1))
641 goto err;
643 vs_update(sp, msg_cat(sp,
644 "169|Confirm change? [n]", NULL), NULL);
646 if (v_event_get(sp, &ev, 0, 0))
647 goto err;
648 switch (ev.e_event) {
649 case E_CHARACTER:
650 break;
651 case E_EOF:
652 case E_ERR:
653 case E_INTERRUPT:
654 goto lquit;
655 default:
656 v_event_err(sp, &ev);
657 goto lquit;
659 } else {
660 if (ex_print(sp, cmdp, &from, &to, 0) ||
661 ex_scprint(sp, &from, &to))
662 goto lquit;
663 if (ex_txt(sp, &tiq, 0, TXT_CR))
664 goto err;
665 ev.e_c = tiq.cqh_first->lb[0];
668 switch (ev.e_c) {
669 case CH_YES:
670 break;
671 default:
672 case CH_NO:
673 didsub = 0;
674 BUILD(sp, s +offset, match[0].rm_eo);
675 goto skip;
676 case CH_QUIT:
677 /* Set the quit/interrupted flags. */
678 lquit: quit = 1;
679 F_SET(sp->gp, G_INTERRUPTED);
682 * Resolve any changes, then return to (and
683 * exit from) the main loop.
685 goto endmatch;
690 * Set the cursor to the last position changed, converting
691 * from 1-based to 0-based.
693 sp->lno = lno;
694 sp->cno = match[0].rm_so;
696 /* Copy the bytes before the match into the build buffer. */
697 BUILD(sp, s + offset, match[0].rm_so);
699 /* Substitute the matching bytes. */
700 didsub = 1;
701 if (re_sub(sp, s + offset, &lb, &lbclen, &lblen, match))
702 goto err;
704 /* Set the change flag so we know this line was modified. */
705 linechanged = 1;
707 /* Move past the matched bytes. */
708 skip: offset += match[0].rm_eo;
709 len -= match[0].rm_eo;
711 /* A match cannot be followed by an empty pattern. */
712 empty_ok = 0;
715 * If doing a global change with confirmation, we have to
716 * update the screen. The basic idea is to store the line
717 * so the screen update routines can find it, and restart.
719 if (didsub && sp->c_suffix && sp->g_suffix) {
721 * The new search offset will be the end of the
722 * modified line.
724 saved_offset = lbclen;
726 /* Copy the rest of the line. */
727 if (len)
728 BUILD(sp, s + offset, len)
730 /* Set the new offset. */
731 offset = saved_offset;
733 /* Store inserted lines, adjusting the build buffer. */
734 last = 0;
735 if (sp->newl_cnt) {
736 for (cnt = 0;
737 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
738 if (db_insert(sp, lno,
739 lb + last, sp->newl[cnt] - last))
740 goto err;
741 last = sp->newl[cnt] + 1;
742 ++sp->rptlines[L_ADDED];
744 lbclen -= last;
745 offset -= last;
746 sp->newl_cnt = 0;
749 /* Store and retrieve the line. */
750 if (db_set(sp, lno, lb + last, lbclen))
751 goto err;
752 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
753 goto err;
754 ADD_SPACE_RET(sp, bp, blen, llen)
755 memcpy(bp, s, llen);
756 s = bp;
757 len = llen - offset;
759 /* Restart the build. */
760 lbclen = 0;
761 BUILD(sp, s, offset);
764 * If we haven't already done the after-the-string
765 * match, do one. Set REG_NOTEOL so the '$' pattern
766 * only matches once.
768 if (!do_eol_match)
769 goto endmatch;
770 if (offset == len) {
771 do_eol_match = 0;
772 eflags |= REG_NOTEOL;
774 goto nextmatch;
778 * If it's a global:
780 * If at the end of the string, do a test for the after
781 * the string match. Set REG_NOTEOL so the '$' pattern
782 * only matches once.
784 if (sp->g_suffix && do_eol_match) {
785 if (len == 0) {
786 do_eol_match = 0;
787 eflags |= REG_NOTEOL;
789 goto nextmatch;
792 endmatch: if (!linechanged)
793 continue;
795 /* Copy any remaining bytes into the build buffer. */
796 if (len)
797 BUILD(sp, s + offset, len)
799 /* Store inserted lines, adjusting the build buffer. */
800 last = 0;
801 if (sp->newl_cnt) {
802 for (cnt = 0;
803 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
804 if (db_insert(sp,
805 lno, lb + last, sp->newl[cnt] - last))
806 goto err;
807 last = sp->newl[cnt] + 1;
808 ++sp->rptlines[L_ADDED];
810 lbclen -= last;
811 sp->newl_cnt = 0;
814 /* Store the changed line. */
815 if (db_set(sp, lno, lb + last, lbclen))
816 goto err;
818 /* Update changed line counter. */
819 if (sp->rptlchange != lno) {
820 sp->rptlchange = lno;
821 ++sp->rptlines[L_CHANGED];
825 * !!!
826 * Display as necessary. Historic practice is to only
827 * display the last line of a line split into multiple
828 * lines.
830 if (lflag || nflag || pflag) {
831 from.lno = to.lno = lno;
832 from.cno = to.cno = 0;
833 if (lflag)
834 (void)ex_print(sp, cmdp, &from, &to, E_C_LIST);
835 if (nflag)
836 (void)ex_print(sp, cmdp, &from, &to, E_C_HASH);
837 if (pflag)
838 (void)ex_print(sp, cmdp, &from, &to, E_C_PRINT);
843 * !!!
844 * Historically, vi attempted to leave the cursor at the same place if
845 * the substitution was done at the current cursor position. Otherwise
846 * it moved it to the first non-blank of the last line changed. There
847 * were some problems: for example, :s/$/foo/ with the cursor on the
848 * last character of the line left the cursor on the last character, or
849 * the & command with multiple occurrences of the matching string in the
850 * line usually left the cursor in a fairly random position.
852 * We try to do the same thing, with the exception that if the user is
853 * doing substitution with confirmation, we move to the last line about
854 * which the user was consulted, as opposed to the last line that they
855 * actually changed. This prevents a screen flash if the user doesn't
856 * change many of the possible lines.
858 if (!sp->c_suffix && (sp->lno != slno || sp->cno != scno)) {
859 sp->cno = 0;
860 (void)nonblank(sp, sp->lno, &sp->cno);
864 * If not in a global command, and nothing matched, say so.
865 * Else, if none of the lines displayed, put something up.
867 rval = 0;
868 if (!matched) {
869 if (!F_ISSET(sp, SC_EX_GLOBAL)) {
870 msgq(sp, M_ERR, "157|No match found");
871 goto err;
873 } else if (!lflag && !nflag && !pflag)
874 F_SET(cmdp, E_AUTOPRINT);
876 if (0) {
877 err: rval = 1;
880 if (bp != NULL)
881 FREE_SPACE(sp, bp, blen);
882 if (lb != NULL)
883 free(lb);
884 return (rval);
888 * re_compile --
889 * Compile the RE.
891 * PUBLIC: int re_compile __P((SCR *,
892 * PUBLIC: char *, size_t, char **, size_t *, regex_t *, u_int));
895 re_compile(sp, ptrn, plen, ptrnp, lenp, rep, flags)
896 SCR *sp;
897 char *ptrn, **ptrnp;
898 size_t plen, *lenp;
899 regex_t *rep;
900 u_int flags;
902 size_t len;
903 int reflags, replaced, rval;
904 char *p;
906 /* Set RE flags. */
907 reflags = 0;
908 if (LF_ISSET(SEARCH_EXTEND))
909 reflags |= REG_EXTENDED;
910 if (LF_ISSET(SEARCH_IC))
911 reflags |= REG_ICASE;
912 if (LF_ISSET(SEARCH_LITERAL))
913 reflags |= REG_NOSPEC;
914 if (!LF_ISSET(SEARCH_NOOPT | SEARCH_CSCOPE | SEARCH_TAG)) {
915 if (O_ISSET(sp, O_EXTENDED))
916 reflags |= REG_EXTENDED;
917 if (O_ISSET(sp, O_IGNORECASE))
918 reflags |= REG_ICASE;
919 if (O_ISSET(sp, O_ICLOWER))
920 goto iclower;
922 if (LF_ISSET(SEARCH_ICL)) {
923 iclower: for (p = ptrn, len = plen; len > 0; ++p, --len)
924 if (isupper(*p))
925 break;
926 if (len == 0)
927 reflags |= REG_ICASE;
930 /* If we're replacing a saved value, clear the old one. */
931 if (LF_ISSET(SEARCH_CSEARCH) && F_ISSET(sp, SC_RE_SEARCH)) {
932 regfree(&sp->re_c);
933 F_CLR(sp, SC_RE_SEARCH);
935 if (LF_ISSET(SEARCH_CSUBST) && F_ISSET(sp, SC_RE_SUBST)) {
936 regfree(&sp->subre_c);
937 F_CLR(sp, SC_RE_SUBST);
941 * If we're saving the string, it's a pattern we haven't seen before,
942 * so convert the vi-style RE's to POSIX 1003.2 RE's. Save a copy for
943 * later recompilation. Free any previously saved value.
945 if (ptrnp != NULL) {
946 replaced = 0;
947 if (LF_ISSET(SEARCH_CSCOPE)) {
948 if (re_cscope_conv(sp, &ptrn, &plen, &replaced))
949 return (1);
951 * XXX
952 * Currently, the match-any-<blank> expression used in
953 * re_cscope_conv() requires extended RE's. This may
954 * not be right or safe.
956 reflags |= REG_EXTENDED;
957 } else if (LF_ISSET(SEARCH_TAG)) {
958 if (re_tag_conv(sp, &ptrn, &plen, &replaced))
959 return (1);
960 } else if (!LF_ISSET(SEARCH_LITERAL))
961 if (re_conv(sp, &ptrn, &plen, &replaced))
962 return (1);
964 /* Discard previous pattern. */
965 if (*ptrnp != NULL) {
966 free(*ptrnp);
967 *ptrnp = NULL;
969 if (lenp != NULL)
970 *lenp = plen;
973 * Copy the string into allocated memory.
975 * XXX
976 * Regcomp isn't 8-bit clean, so the pattern is nul-terminated
977 * for now. There's just no other solution.
979 MALLOC(sp, *ptrnp, char *, plen + 1);
980 if (*ptrnp != NULL) {
981 memcpy(*ptrnp, ptrn, plen);
982 (*ptrnp)[plen] = '\0';
985 /* Free up conversion-routine-allocated memory. */
986 if (replaced)
987 FREE_SPACE(sp, ptrn, 0);
989 if (*ptrnp == NULL)
990 return (1);
992 ptrn = *ptrnp;
996 * XXX
997 * Regcomp isn't 8-bit clean, so we just lost if the pattern
998 * contained a nul. Bummer!
1000 if ((rval = regcomp(rep, ptrn, /* plen, */ reflags)) != 0) {
1001 if (LF_ISSET(SEARCH_MSG))
1002 re_error(sp, rval, rep);
1003 return (1);
1006 if (LF_ISSET(SEARCH_CSEARCH))
1007 F_SET(sp, SC_RE_SEARCH);
1008 if (LF_ISSET(SEARCH_CSUBST))
1009 F_SET(sp, SC_RE_SUBST);
1011 return (0);
1015 * re_conv --
1016 * Convert vi's regular expressions into something that the
1017 * the POSIX 1003.2 RE functions can handle.
1019 * There are three conversions we make to make vi's RE's (specifically
1020 * the global, search, and substitute patterns) work with POSIX RE's.
1022 * 1: If O_MAGIC is not set, strip backslashes from the magic character
1023 * set (.[*~) that have them, and add them to the ones that don't.
1024 * 2: If O_MAGIC is not set, the string "\~" is replaced with the text
1025 * from the last substitute command's replacement string. If O_MAGIC
1026 * is set, it's the string "~".
1027 * 3: The pattern \<ptrn\> does "word" searches, convert it to use the
1028 * new RE escapes.
1030 * !!!/XXX
1031 * This doesn't exactly match the historic behavior of vi because we do
1032 * the ~ substitution before calling the RE engine, so magic characters
1033 * in the replacement string will be expanded by the RE engine, and they
1034 * weren't historically. It's a bug.
1036 static int
1037 re_conv(sp, ptrnp, plenp, replacedp)
1038 SCR *sp;
1039 char **ptrnp;
1040 size_t *plenp;
1041 int *replacedp;
1043 size_t blen, len, needlen;
1044 int magic;
1045 char *bp, *p, *t;
1048 * First pass through, we figure out how much space we'll need.
1049 * We do it in two passes, on the grounds that most of the time
1050 * the user is doing a search and won't have magic characters.
1051 * That way we can skip most of the memory allocation and copies.
1053 magic = 0;
1054 for (p = *ptrnp, len = *plenp, needlen = 0; len > 0; ++p, --len)
1055 switch (*p) {
1056 case '\\':
1057 if (len > 1) {
1058 --len;
1059 switch (*++p) {
1060 case '<':
1061 magic = 1;
1062 needlen += sizeof(RE_WSTART);
1063 break;
1064 case '>':
1065 magic = 1;
1066 needlen += sizeof(RE_WSTOP);
1067 break;
1068 case '~':
1069 if (!O_ISSET(sp, O_MAGIC)) {
1070 magic = 1;
1071 needlen += sp->repl_len;
1073 break;
1074 case '.':
1075 case '[':
1076 case '*':
1077 if (!O_ISSET(sp, O_MAGIC)) {
1078 magic = 1;
1079 needlen += 1;
1081 break;
1082 default:
1083 needlen += 2;
1085 } else
1086 needlen += 1;
1087 break;
1088 case '~':
1089 if (O_ISSET(sp, O_MAGIC)) {
1090 magic = 1;
1091 needlen += sp->repl_len;
1093 break;
1094 case '.':
1095 case '[':
1096 case '*':
1097 if (!O_ISSET(sp, O_MAGIC)) {
1098 magic = 1;
1099 needlen += 2;
1101 break;
1102 default:
1103 needlen += 1;
1104 break;
1107 if (!magic) {
1108 *replacedp = 0;
1109 return (0);
1112 /* Get enough memory to hold the final pattern. */
1113 *replacedp = 1;
1114 GET_SPACE_RET(sp, bp, blen, needlen);
1116 for (p = *ptrnp, len = *plenp, t = bp; len > 0; ++p, --len)
1117 switch (*p) {
1118 case '\\':
1119 if (len > 1) {
1120 --len;
1121 switch (*++p) {
1122 case '<':
1123 memcpy(t,
1124 RE_WSTART, sizeof(RE_WSTART) - 1);
1125 t += sizeof(RE_WSTART) - 1;
1126 break;
1127 case '>':
1128 memcpy(t,
1129 RE_WSTOP, sizeof(RE_WSTOP) - 1);
1130 t += sizeof(RE_WSTOP) - 1;
1131 break;
1132 case '~':
1133 if (O_ISSET(sp, O_MAGIC))
1134 *t++ = '~';
1135 else {
1136 memcpy(t,
1137 sp->repl, sp->repl_len);
1138 t += sp->repl_len;
1140 break;
1141 case '.':
1142 case '[':
1143 case '*':
1144 if (O_ISSET(sp, O_MAGIC))
1145 *t++ = '\\';
1146 *t++ = *p;
1147 break;
1148 default:
1149 *t++ = '\\';
1150 *t++ = *p;
1152 } else
1153 *t++ = '\\';
1154 break;
1155 case '~':
1156 if (O_ISSET(sp, O_MAGIC)) {
1157 memcpy(t, sp->repl, sp->repl_len);
1158 t += sp->repl_len;
1159 } else
1160 *t++ = '~';
1161 break;
1162 case '.':
1163 case '[':
1164 case '*':
1165 if (!O_ISSET(sp, O_MAGIC))
1166 *t++ = '\\';
1167 *t++ = *p;
1168 break;
1169 default:
1170 *t++ = *p;
1171 break;
1174 *ptrnp = bp;
1175 *plenp = t - bp;
1176 return (0);
1180 * re_tag_conv --
1181 * Convert a tags search path into something that the POSIX
1182 * 1003.2 RE functions can handle.
1184 static int
1185 re_tag_conv(sp, ptrnp, plenp, replacedp)
1186 SCR *sp;
1187 char **ptrnp;
1188 size_t *plenp;
1189 int *replacedp;
1191 size_t blen, len;
1192 int lastdollar;
1193 char *bp, *p, *t;
1195 len = *plenp;
1197 /* Max memory usage is 2 times the length of the string. */
1198 *replacedp = 1;
1199 GET_SPACE_RET(sp, bp, blen, len * 2);
1201 p = *ptrnp;
1202 t = bp;
1204 /* If the last character is a '/' or '?', we just strip it. */
1205 if (len > 0 && (p[len - 1] == '/' || p[len - 1] == '?'))
1206 --len;
1208 /* If the next-to-last or last character is a '$', it's magic. */
1209 if (len > 0 && p[len - 1] == '$') {
1210 --len;
1211 lastdollar = 1;
1212 } else
1213 lastdollar = 0;
1215 /* If the first character is a '/' or '?', we just strip it. */
1216 if (len > 0 && (p[0] == '/' || p[0] == '?')) {
1217 ++p;
1218 --len;
1221 /* If the first or second character is a '^', it's magic. */
1222 if (p[0] == '^') {
1223 *t++ = *p++;
1224 --len;
1228 * Escape every other magic character we can find, meanwhile stripping
1229 * the backslashes ctags inserts when escaping the search delimiter
1230 * characters.
1232 for (; len > 0; --len) {
1233 if (p[0] == '\\' && (p[1] == '/' || p[1] == '?')) {
1234 ++p;
1235 --len;
1236 } else if (strchr("^.[]$*", p[0]))
1237 *t++ = '\\';
1238 *t++ = *p++;
1240 if (lastdollar)
1241 *t++ = '$';
1243 *ptrnp = bp;
1244 *plenp = t - bp;
1245 return (0);
1249 * re_cscope_conv --
1250 * Convert a cscope search path into something that the POSIX
1251 * 1003.2 RE functions can handle.
1253 static int
1254 re_cscope_conv(sp, ptrnp, plenp, replacedp)
1255 SCR *sp;
1256 char **ptrnp;
1257 size_t *plenp;
1258 int *replacedp;
1260 size_t blen, len, nspaces;
1261 char *bp, *p, *t;
1264 * Each space in the source line printed by cscope represents an
1265 * arbitrary sequence of spaces, tabs, and comments.
1267 #define CSCOPE_RE_SPACE "([ \t]|/\\*([^*]|\\*/)*\\*/)*"
1268 for (nspaces = 0, p = *ptrnp, len = *plenp; len > 0; ++p, --len)
1269 if (*p == ' ')
1270 ++nspaces;
1273 * Allocate plenty of space:
1274 * the string, plus potential escaping characters;
1275 * nspaces + 2 copies of CSCOPE_RE_SPACE;
1276 * ^, $, nul terminator characters.
1278 *replacedp = 1;
1279 len = (p - *ptrnp) * 2 + (nspaces + 2) * sizeof(CSCOPE_RE_SPACE) + 3;
1280 GET_SPACE_RET(sp, bp, blen, len);
1282 p = *ptrnp;
1283 t = bp;
1285 *t++ = '^';
1286 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1287 t += sizeof(CSCOPE_RE_SPACE) - 1;
1289 for (len = *plenp; len > 0; ++p, --len)
1290 if (*p == ' ') {
1291 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1292 t += sizeof(CSCOPE_RE_SPACE) - 1;
1293 } else {
1294 if (strchr("\\^.[]$*+?()|{}", *p))
1295 *t++ = '\\';
1296 *t++ = *p;
1299 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1300 t += sizeof(CSCOPE_RE_SPACE) - 1;
1301 *t++ = '$';
1303 *ptrnp = bp;
1304 *plenp = t - bp;
1305 return (0);
1309 * re_error --
1310 * Report a regular expression error.
1312 * PUBLIC: void re_error __P((SCR *, int, regex_t *));
1314 void
1315 re_error(sp, errcode, preg)
1316 SCR *sp;
1317 int errcode;
1318 regex_t *preg;
1320 size_t s;
1321 char *oe;
1323 s = regerror(errcode, preg, "", 0);
1324 if ((oe = malloc(s)) == NULL)
1325 msgq(sp, M_SYSERR, NULL);
1326 else {
1327 (void)regerror(errcode, preg, oe, s);
1328 msgq(sp, M_ERR, "RE error: %s", oe);
1329 free(oe);
1334 * re_sub --
1335 * Do the substitution for a regular expression.
1337 static int
1338 re_sub(sp, ip, lbp, lbclenp, lblenp, match)
1339 SCR *sp;
1340 char *ip; /* Input line. */
1341 char **lbp;
1342 size_t *lbclenp, *lblenp;
1343 regmatch_t match[10];
1345 enum { C_NOTSET, C_LOWER, C_ONELOWER, C_ONEUPPER, C_UPPER } conv;
1346 size_t lbclen, lblen; /* Local copies. */
1347 size_t mlen; /* Match length. */
1348 size_t rpl; /* Remaining replacement length. */
1349 char *rp; /* Replacement pointer. */
1350 int ch;
1351 int no; /* Match replacement offset. */
1352 char *p, *t; /* Buffer pointers. */
1353 char *lb; /* Local copies. */
1355 lb = *lbp; /* Get local copies. */
1356 lbclen = *lbclenp;
1357 lblen = *lblenp;
1360 * QUOTING NOTE:
1362 * There are some special sequences that vi provides in the
1363 * replacement patterns.
1364 * & string the RE matched (\& if nomagic set)
1365 * \# n-th regular subexpression
1366 * \E end \U, \L conversion
1367 * \e end \U, \L conversion
1368 * \l convert the next character to lower-case
1369 * \L convert to lower-case, until \E, \e, or end of replacement
1370 * \u convert the next character to upper-case
1371 * \U convert to upper-case, until \E, \e, or end of replacement
1373 * Otherwise, since this is the lowest level of replacement, discard
1374 * all escaping characters. This (hopefully) matches historic practice.
1376 #define OUTCH(ch, nltrans) { \
1377 CHAR_T __ch = (ch); \
1378 u_int __value = KEY_VAL(sp, __ch); \
1379 if (nltrans && (__value == K_CR || __value == K_NL)) { \
1380 NEEDNEWLINE(sp); \
1381 sp->newl[sp->newl_cnt++] = lbclen; \
1382 } else if (conv != C_NOTSET) { \
1383 switch (conv) { \
1384 case C_ONELOWER: \
1385 conv = C_NOTSET; \
1386 /* FALLTHROUGH */ \
1387 case C_LOWER: \
1388 if (isupper(__ch)) \
1389 __ch = tolower(__ch); \
1390 break; \
1391 case C_ONEUPPER: \
1392 conv = C_NOTSET; \
1393 /* FALLTHROUGH */ \
1394 case C_UPPER: \
1395 if (islower(__ch)) \
1396 __ch = toupper(__ch); \
1397 break; \
1398 default: \
1399 abort(); \
1402 NEEDSP(sp, 1, p); \
1403 *p++ = __ch; \
1404 ++lbclen; \
1406 conv = C_NOTSET;
1407 for (rp = sp->repl, rpl = sp->repl_len, p = lb + lbclen; rpl--;) {
1408 switch (ch = *rp++) {
1409 case '&':
1410 if (O_ISSET(sp, O_MAGIC)) {
1411 no = 0;
1412 goto subzero;
1414 break;
1415 case '\\':
1416 if (rpl == 0)
1417 break;
1418 --rpl;
1419 switch (ch = *rp) {
1420 case '&':
1421 ++rp;
1422 if (!O_ISSET(sp, O_MAGIC)) {
1423 no = 0;
1424 goto subzero;
1426 break;
1427 case '0': case '1': case '2': case '3': case '4':
1428 case '5': case '6': case '7': case '8': case '9':
1429 no = *rp++ - '0';
1430 subzero: if (match[no].rm_so == -1 ||
1431 match[no].rm_eo == -1)
1432 break;
1433 mlen = match[no].rm_eo - match[no].rm_so;
1434 for (t = ip + match[no].rm_so; mlen--; ++t)
1435 OUTCH(*t, 0);
1436 continue;
1437 case 'e':
1438 case 'E':
1439 ++rp;
1440 conv = C_NOTSET;
1441 continue;
1442 case 'l':
1443 ++rp;
1444 conv = C_ONELOWER;
1445 continue;
1446 case 'L':
1447 ++rp;
1448 conv = C_LOWER;
1449 continue;
1450 case 'u':
1451 ++rp;
1452 conv = C_ONEUPPER;
1453 continue;
1454 case 'U':
1455 ++rp;
1456 conv = C_UPPER;
1457 continue;
1458 default:
1459 ++rp;
1460 break;
1463 OUTCH(ch, 1);
1466 *lbp = lb; /* Update caller's information. */
1467 *lbclenp = lbclen;
1468 *lblenp = lblen;
1469 return (0);