clean up naming, add select functions
[nvi.git] / ex / ex_subst.c
blob613c0c2cbae09d0be02379b178837374f0736e6b
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.40 1997/01/13 18:27:54 bostic Exp $ (Berkeley) $Date: 1997/01/13 18:27:54 $";
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 lno = cmdp->addr1.lno == 0 ? 1 : cmdp->addr1.lno;
502 for (matched = quit = 0,
503 elno = cmdp->addr2.lno; !quit && lno <= elno; ++lno) {
505 /* Someone's unhappy, time to stop. */
506 if (INTERRUPTED(sp))
507 break;
509 /* Get the line. */
510 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
511 goto err;
514 * Make a local copy if doing confirmation -- when calling
515 * the confirm routine we're likely to lose the cached copy.
517 if (sp->c_suffix) {
518 if (bp == NULL) {
519 GET_SPACE_RET(sp, bp, blen, llen);
520 } else
521 ADD_SPACE_RET(sp, bp, blen, llen);
522 memcpy(bp, s, llen);
523 s = bp;
526 /* Start searching from the beginning. */
527 offset = 0;
528 len = llen;
530 /* Reset the build buffer offset. */
531 lbclen = 0;
533 /* Reset empty match flag. */
534 empty_ok = 1;
537 * We don't want to have to do a setline if the line didn't
538 * change -- keep track of whether or not this line changed.
539 * If doing confirmations, don't want to keep setting the
540 * line if change is refused -- keep track of substitutions.
542 didsub = linechanged = 0;
544 /* New line, do an EOL match. */
545 do_eol_match = 1;
547 /* It's not nul terminated, but we pretend it is. */
548 eflags = REG_STARTEND;
551 * The search area is from s + offset to the EOL.
553 * Generally, match[0].rm_so is the offset of the start
554 * of the match from the start of the search, and offset
555 * is the offset of the start of the last search.
557 nextmatch: match[0].rm_so = 0;
558 match[0].rm_eo = len;
560 /* Get the next match. */
561 eval = regexec(re, (char *)s + offset, 10, match, eflags);
564 * There wasn't a match or if there was an error, deal with
565 * it. If there was a previous match in this line, resolve
566 * the changes into the database. Otherwise, just move on.
568 if (eval == REG_NOMATCH)
569 goto endmatch;
570 if (eval != 0) {
571 re_error(sp, eval, re);
572 goto err;
574 matched = 1;
576 /* Only the first search can match an anchored expression. */
577 eflags |= REG_NOTBOL;
580 * !!!
581 * It's possible to match 0-length strings -- for example, the
582 * command s;a*;X;, when matched against the string "aabb" will
583 * result in "XbXbX", i.e. the matches are "aa", the space
584 * between the b's and the space between the b's and the end of
585 * the string. There is a similar space between the beginning
586 * of the string and the a's. The rule that we use (because vi
587 * historically used it) is that any 0-length match, occurring
588 * immediately after a match, is ignored. Otherwise, the above
589 * example would have resulted in "XXbXbX". Another example is
590 * incorrectly using " *" to replace groups of spaces with one
591 * space.
593 * The way we do this is that if we just had a successful match,
594 * the starting offset does not skip characters, and the match
595 * is empty, ignore the match and move forward. If there's no
596 * more characters in the string, we were attempting to match
597 * after the last character, so quit.
599 if (!empty_ok && match[0].rm_so == 0 && match[0].rm_eo == 0) {
600 empty_ok = 1;
601 if (len == 0)
602 goto endmatch;
603 BUILD(sp, s + offset, 1)
604 ++offset;
605 --len;
606 goto nextmatch;
609 /* Confirm change. */
610 if (sp->c_suffix) {
612 * Set the cursor position for confirmation. Note,
613 * if we matched on a '$', the cursor may be past
614 * the end of line.
616 from.lno = to.lno = lno;
617 from.cno = match[0].rm_so + offset;
618 to.cno = match[0].rm_eo + offset;
620 * Both ex and vi have to correct for a change before
621 * the first character in the line.
623 if (llen == 0)
624 from.cno = to.cno = 0;
625 if (F_ISSET(sp, SC_VI)) {
627 * Only vi has to correct for a change after
628 * the last character in the line.
630 * XXX
631 * It would be nice to change the vi code so
632 * that we could display a cursor past EOL.
634 if (to.cno >= llen)
635 to.cno = llen - 1;
636 if (from.cno >= llen)
637 from.cno = llen - 1;
639 sp->lno = from.lno;
640 sp->cno = from.cno;
641 if (vs_refresh(sp, 1))
642 goto err;
644 vs_update(sp, msg_cat(sp,
645 "169|Confirm change? [n]", NULL), NULL);
647 if (v_event_get(sp, &ev, 0, 0))
648 goto err;
649 switch (ev.e_event) {
650 case E_CHARACTER:
651 break;
652 case E_EOF:
653 case E_ERR:
654 case E_INTERRUPT:
655 goto lquit;
656 default:
657 v_event_err(sp, &ev);
658 goto lquit;
660 } else {
661 if (ex_print(sp, cmdp, &from, &to, 0) ||
662 ex_scprint(sp, &from, &to))
663 goto lquit;
664 if (ex_txt(sp, &tiq, 0, TXT_CR))
665 goto err;
666 ev.e_c = tiq.cqh_first->lb[0];
669 switch (ev.e_c) {
670 case CH_YES:
671 break;
672 default:
673 case CH_NO:
674 didsub = 0;
675 BUILD(sp, s +offset, match[0].rm_eo);
676 goto skip;
677 case CH_QUIT:
678 /* Set the quit/interrupted flags. */
679 lquit: quit = 1;
680 F_SET(sp->gp, G_INTERRUPTED);
683 * Resolve any changes, then return to (and
684 * exit from) the main loop.
686 goto endmatch;
691 * Set the cursor to the last position changed, converting
692 * from 1-based to 0-based.
694 sp->lno = lno;
695 sp->cno = match[0].rm_so;
697 /* Copy the bytes before the match into the build buffer. */
698 BUILD(sp, s + offset, match[0].rm_so);
700 /* Substitute the matching bytes. */
701 didsub = 1;
702 if (re_sub(sp, s + offset, &lb, &lbclen, &lblen, match))
703 goto err;
705 /* Set the change flag so we know this line was modified. */
706 linechanged = 1;
708 /* Move past the matched bytes. */
709 skip: offset += match[0].rm_eo;
710 len -= match[0].rm_eo;
712 /* A match cannot be followed by an empty pattern. */
713 empty_ok = 0;
716 * If doing a global change with confirmation, we have to
717 * update the screen. The basic idea is to store the line
718 * so the screen update routines can find it, and restart.
720 if (didsub && sp->c_suffix && sp->g_suffix) {
722 * The new search offset will be the end of the
723 * modified line.
725 saved_offset = lbclen;
727 /* Copy the rest of the line. */
728 if (len)
729 BUILD(sp, s + offset, len)
731 /* Set the new offset. */
732 offset = saved_offset;
734 /* Store inserted lines, adjusting the build buffer. */
735 last = 0;
736 if (sp->newl_cnt) {
737 for (cnt = 0;
738 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
739 if (db_insert(sp, lno,
740 lb + last, sp->newl[cnt] - last))
741 goto err;
742 last = sp->newl[cnt] + 1;
743 ++sp->rptlines[L_ADDED];
745 lbclen -= last;
746 offset -= last;
747 sp->newl_cnt = 0;
750 /* Store and retrieve the line. */
751 if (db_set(sp, lno, lb + last, lbclen))
752 goto err;
753 if (db_get(sp, lno, DBG_FATAL, &s, &llen))
754 goto err;
755 ADD_SPACE_RET(sp, bp, blen, llen)
756 memcpy(bp, s, llen);
757 s = bp;
758 len = llen - offset;
760 /* Restart the build. */
761 lbclen = 0;
762 BUILD(sp, s, offset);
765 * If we haven't already done the after-the-string
766 * match, do one. Set REG_NOTEOL so the '$' pattern
767 * only matches once.
769 if (!do_eol_match)
770 goto endmatch;
771 if (offset == len) {
772 do_eol_match = 0;
773 eflags |= REG_NOTEOL;
775 goto nextmatch;
779 * If it's a global:
781 * If at the end of the string, do a test for the after
782 * the string match. Set REG_NOTEOL so the '$' pattern
783 * only matches once.
785 if (sp->g_suffix && do_eol_match) {
786 if (len == 0) {
787 do_eol_match = 0;
788 eflags |= REG_NOTEOL;
790 goto nextmatch;
793 endmatch: if (!linechanged)
794 continue;
796 /* Copy any remaining bytes into the build buffer. */
797 if (len)
798 BUILD(sp, s + offset, len)
800 /* Store inserted lines, adjusting the build buffer. */
801 last = 0;
802 if (sp->newl_cnt) {
803 for (cnt = 0;
804 cnt < sp->newl_cnt; ++cnt, ++lno, ++elno) {
805 if (db_insert(sp,
806 lno, lb + last, sp->newl[cnt] - last))
807 goto err;
808 last = sp->newl[cnt] + 1;
809 ++sp->rptlines[L_ADDED];
811 lbclen -= last;
812 sp->newl_cnt = 0;
815 /* Store the changed line. */
816 if (db_set(sp, lno, lb + last, lbclen))
817 goto err;
819 /* Update changed line counter. */
820 if (sp->rptlchange != lno) {
821 sp->rptlchange = lno;
822 ++sp->rptlines[L_CHANGED];
826 * !!!
827 * Display as necessary. Historic practice is to only
828 * display the last line of a line split into multiple
829 * lines.
831 if (lflag || nflag || pflag) {
832 from.lno = to.lno = lno;
833 from.cno = to.cno = 0;
834 if (lflag)
835 (void)ex_print(sp, cmdp, &from, &to, E_C_LIST);
836 if (nflag)
837 (void)ex_print(sp, cmdp, &from, &to, E_C_HASH);
838 if (pflag)
839 (void)ex_print(sp, cmdp, &from, &to, E_C_PRINT);
844 * !!!
845 * Historically, vi attempted to leave the cursor at the same place if
846 * the substitution was done at the current cursor position. Otherwise
847 * it moved it to the first non-blank of the last line changed. There
848 * were some problems: for example, :s/$/foo/ with the cursor on the
849 * last character of the line left the cursor on the last character, or
850 * the & command with multiple occurrences of the matching string in the
851 * line usually left the cursor in a fairly random position.
853 * We try to do the same thing, with the exception that if the user is
854 * doing substitution with confirmation, we move to the last line about
855 * which the user was consulted, as opposed to the last line that they
856 * actually changed. This prevents a screen flash if the user doesn't
857 * change many of the possible lines.
859 if (!sp->c_suffix && (sp->lno != slno || sp->cno != scno)) {
860 sp->cno = 0;
861 (void)nonblank(sp, sp->lno, &sp->cno);
865 * If not in a global command, and nothing matched, say so.
866 * Else, if none of the lines displayed, put something up.
868 rval = 0;
869 if (!matched) {
870 if (!F_ISSET(sp, SC_EX_GLOBAL)) {
871 msgq(sp, M_ERR, "157|No match found");
872 goto err;
874 } else if (!lflag && !nflag && !pflag)
875 F_SET(cmdp, E_AUTOPRINT);
877 if (0) {
878 err: rval = 1;
881 if (bp != NULL)
882 FREE_SPACE(sp, bp, blen);
883 if (lb != NULL)
884 free(lb);
885 return (rval);
889 * re_compile --
890 * Compile the RE.
892 * PUBLIC: int re_compile __P((SCR *,
893 * PUBLIC: char *, size_t, char **, size_t *, regex_t *, u_int));
896 re_compile(sp, ptrn, plen, ptrnp, lenp, rep, flags)
897 SCR *sp;
898 char *ptrn, **ptrnp;
899 size_t plen, *lenp;
900 regex_t *rep;
901 u_int flags;
903 size_t len;
904 int reflags, replaced, rval;
905 char *p;
907 /* Set RE flags. */
908 reflags = 0;
909 if (LF_ISSET(SEARCH_EXTEND))
910 reflags |= REG_EXTENDED;
911 if (LF_ISSET(SEARCH_IC))
912 reflags |= REG_ICASE;
913 if (LF_ISSET(SEARCH_LITERAL))
914 reflags |= REG_NOSPEC;
915 if (!LF_ISSET(SEARCH_NOOPT | SEARCH_CSCOPE | SEARCH_TAG)) {
916 if (O_ISSET(sp, O_EXTENDED))
917 reflags |= REG_EXTENDED;
918 if (O_ISSET(sp, O_IGNORECASE))
919 reflags |= REG_ICASE;
920 if (O_ISSET(sp, O_ICLOWER))
921 goto iclower;
923 if (LF_ISSET(SEARCH_ICL)) {
924 iclower: for (p = ptrn, len = plen; len > 0; ++p, --len)
925 if (isupper(*p))
926 break;
927 if (len == 0)
928 reflags |= REG_ICASE;
931 /* If we're replacing a saved value, clear the old one. */
932 if (LF_ISSET(SEARCH_CSEARCH) && F_ISSET(sp, SC_RE_SEARCH)) {
933 regfree(&sp->re_c);
934 F_CLR(sp, SC_RE_SEARCH);
936 if (LF_ISSET(SEARCH_CSUBST) && F_ISSET(sp, SC_RE_SUBST)) {
937 regfree(&sp->subre_c);
938 F_CLR(sp, SC_RE_SUBST);
942 * If we're saving the string, it's a pattern we haven't seen before,
943 * so convert the vi-style RE's to POSIX 1003.2 RE's. Save a copy for
944 * later recompilation. Free any previously saved value.
946 if (ptrnp != NULL) {
947 replaced = 0;
948 if (LF_ISSET(SEARCH_CSCOPE)) {
949 if (re_cscope_conv(sp, &ptrn, &plen, &replaced))
950 return (1);
952 * XXX
953 * Currently, the match-any-<blank> expression used in
954 * re_cscope_conv() requires extended RE's. This may
955 * not be right or safe.
957 reflags |= REG_EXTENDED;
958 } else if (LF_ISSET(SEARCH_TAG)) {
959 if (re_tag_conv(sp, &ptrn, &plen, &replaced))
960 return (1);
961 } else if (!LF_ISSET(SEARCH_LITERAL))
962 if (re_conv(sp, &ptrn, &plen, &replaced))
963 return (1);
965 /* Discard previous pattern. */
966 if (*ptrnp != NULL) {
967 free(*ptrnp);
968 *ptrnp = NULL;
970 if (lenp != NULL)
971 *lenp = plen;
974 * Copy the string into allocated memory.
976 * XXX
977 * Regcomp isn't 8-bit clean, so the pattern is nul-terminated
978 * for now. There's just no other solution.
980 MALLOC(sp, *ptrnp, char *, plen + 1);
981 if (*ptrnp != NULL) {
982 memcpy(*ptrnp, ptrn, plen);
983 (*ptrnp)[plen] = '\0';
986 /* Free up conversion-routine-allocated memory. */
987 if (replaced)
988 FREE_SPACE(sp, ptrn, 0);
990 if (*ptrnp == NULL)
991 return (1);
993 ptrn = *ptrnp;
997 * XXX
998 * Regcomp isn't 8-bit clean, so we just lost if the pattern
999 * contained a nul. Bummer!
1001 if ((rval = regcomp(rep, ptrn, /* plen, */ reflags)) != 0) {
1002 if (LF_ISSET(SEARCH_MSG))
1003 re_error(sp, rval, rep);
1004 return (1);
1007 if (LF_ISSET(SEARCH_CSEARCH))
1008 F_SET(sp, SC_RE_SEARCH);
1009 if (LF_ISSET(SEARCH_CSUBST))
1010 F_SET(sp, SC_RE_SUBST);
1012 return (0);
1016 * re_conv --
1017 * Convert vi's regular expressions into something that the
1018 * the POSIX 1003.2 RE functions can handle.
1020 * There are three conversions we make to make vi's RE's (specifically
1021 * the global, search, and substitute patterns) work with POSIX RE's.
1023 * 1: If O_MAGIC is not set, strip backslashes from the magic character
1024 * set (.[*~) that have them, and add them to the ones that don't.
1025 * 2: If O_MAGIC is not set, the string "\~" is replaced with the text
1026 * from the last substitute command's replacement string. If O_MAGIC
1027 * is set, it's the string "~".
1028 * 3: The pattern \<ptrn\> does "word" searches, convert it to use the
1029 * new RE escapes.
1031 * !!!/XXX
1032 * This doesn't exactly match the historic behavior of vi because we do
1033 * the ~ substitution before calling the RE engine, so magic characters
1034 * in the replacement string will be expanded by the RE engine, and they
1035 * weren't historically. It's a bug.
1037 static int
1038 re_conv(sp, ptrnp, plenp, replacedp)
1039 SCR *sp;
1040 char **ptrnp;
1041 size_t *plenp;
1042 int *replacedp;
1044 size_t blen, len, needlen;
1045 int magic;
1046 char *bp, *p, *t;
1049 * First pass through, we figure out how much space we'll need.
1050 * We do it in two passes, on the grounds that most of the time
1051 * the user is doing a search and won't have magic characters.
1052 * That way we can skip most of the memory allocation and copies.
1054 magic = 0;
1055 for (p = *ptrnp, len = *plenp, needlen = 0; len > 0; ++p, --len)
1056 switch (*p) {
1057 case '\\':
1058 if (len > 1) {
1059 --len;
1060 switch (*++p) {
1061 case '<':
1062 magic = 1;
1063 needlen += sizeof(RE_WSTART);
1064 break;
1065 case '>':
1066 magic = 1;
1067 needlen += sizeof(RE_WSTOP);
1068 break;
1069 case '~':
1070 if (!O_ISSET(sp, O_MAGIC)) {
1071 magic = 1;
1072 needlen += sp->repl_len;
1074 break;
1075 case '.':
1076 case '[':
1077 case '*':
1078 if (!O_ISSET(sp, O_MAGIC)) {
1079 magic = 1;
1080 needlen += 1;
1082 break;
1083 default:
1084 needlen += 2;
1086 } else
1087 needlen += 1;
1088 break;
1089 case '~':
1090 if (O_ISSET(sp, O_MAGIC)) {
1091 magic = 1;
1092 needlen += sp->repl_len;
1094 break;
1095 case '.':
1096 case '[':
1097 case '*':
1098 if (!O_ISSET(sp, O_MAGIC)) {
1099 magic = 1;
1100 needlen += 2;
1102 break;
1103 default:
1104 needlen += 1;
1105 break;
1108 if (!magic) {
1109 *replacedp = 0;
1110 return (0);
1113 /* Get enough memory to hold the final pattern. */
1114 *replacedp = 1;
1115 GET_SPACE_RET(sp, bp, blen, needlen);
1117 for (p = *ptrnp, len = *plenp, t = bp; len > 0; ++p, --len)
1118 switch (*p) {
1119 case '\\':
1120 if (len > 1) {
1121 --len;
1122 switch (*++p) {
1123 case '<':
1124 memcpy(t,
1125 RE_WSTART, sizeof(RE_WSTART) - 1);
1126 t += sizeof(RE_WSTART) - 1;
1127 break;
1128 case '>':
1129 memcpy(t,
1130 RE_WSTOP, sizeof(RE_WSTOP) - 1);
1131 t += sizeof(RE_WSTOP) - 1;
1132 break;
1133 case '~':
1134 if (O_ISSET(sp, O_MAGIC))
1135 *t++ = '~';
1136 else {
1137 memcpy(t,
1138 sp->repl, sp->repl_len);
1139 t += sp->repl_len;
1141 break;
1142 case '.':
1143 case '[':
1144 case '*':
1145 if (O_ISSET(sp, O_MAGIC))
1146 *t++ = '\\';
1147 *t++ = *p;
1148 break;
1149 default:
1150 *t++ = '\\';
1151 *t++ = *p;
1153 } else
1154 *t++ = '\\';
1155 break;
1156 case '~':
1157 if (O_ISSET(sp, O_MAGIC)) {
1158 memcpy(t, sp->repl, sp->repl_len);
1159 t += sp->repl_len;
1160 } else
1161 *t++ = '~';
1162 break;
1163 case '.':
1164 case '[':
1165 case '*':
1166 if (!O_ISSET(sp, O_MAGIC))
1167 *t++ = '\\';
1168 *t++ = *p;
1169 break;
1170 default:
1171 *t++ = *p;
1172 break;
1175 *ptrnp = bp;
1176 *plenp = t - bp;
1177 return (0);
1181 * re_tag_conv --
1182 * Convert a tags search path into something that the POSIX
1183 * 1003.2 RE functions can handle.
1185 static int
1186 re_tag_conv(sp, ptrnp, plenp, replacedp)
1187 SCR *sp;
1188 char **ptrnp;
1189 size_t *plenp;
1190 int *replacedp;
1192 size_t blen, len;
1193 int lastdollar;
1194 char *bp, *p, *t;
1196 len = *plenp;
1198 /* Max memory usage is 2 times the length of the string. */
1199 *replacedp = 1;
1200 GET_SPACE_RET(sp, bp, blen, len * 2);
1202 p = *ptrnp;
1203 t = bp;
1205 /* If the last character is a '/' or '?', we just strip it. */
1206 if (len > 0 && (p[len - 1] == '/' || p[len - 1] == '?'))
1207 --len;
1209 /* If the next-to-last or last character is a '$', it's magic. */
1210 if (len > 0 && p[len - 1] == '$') {
1211 --len;
1212 lastdollar = 1;
1213 } else
1214 lastdollar = 0;
1216 /* If the first character is a '/' or '?', we just strip it. */
1217 if (len > 0 && (p[0] == '/' || p[0] == '?')) {
1218 ++p;
1219 --len;
1222 /* If the first or second character is a '^', it's magic. */
1223 if (p[0] == '^') {
1224 *t++ = *p++;
1225 --len;
1229 * Escape every other magic character we can find, meanwhile stripping
1230 * the backslashes ctags inserts when escaping the search delimiter
1231 * characters.
1233 for (; len > 0; --len) {
1234 if (p[0] == '\\' && (p[1] == '/' || p[1] == '?')) {
1235 ++p;
1236 --len;
1237 } else if (strchr("^.[]$*", p[0]))
1238 *t++ = '\\';
1239 *t++ = *p++;
1241 if (lastdollar)
1242 *t++ = '$';
1244 *ptrnp = bp;
1245 *plenp = t - bp;
1246 return (0);
1250 * re_cscope_conv --
1251 * Convert a cscope search path into something that the POSIX
1252 * 1003.2 RE functions can handle.
1254 static int
1255 re_cscope_conv(sp, ptrnp, plenp, replacedp)
1256 SCR *sp;
1257 char **ptrnp;
1258 size_t *plenp;
1259 int *replacedp;
1261 size_t blen, len, nspaces;
1262 char *bp, *p, *t;
1265 * Each space in the source line printed by cscope represents an
1266 * arbitrary sequence of spaces, tabs, and comments.
1268 #define CSCOPE_RE_SPACE "([ \t]|/\\*([^*]|\\*/)*\\*/)*"
1269 for (nspaces = 0, p = *ptrnp, len = *plenp; len > 0; ++p, --len)
1270 if (*p == ' ')
1271 ++nspaces;
1274 * Allocate plenty of space:
1275 * the string, plus potential escaping characters;
1276 * nspaces + 2 copies of CSCOPE_RE_SPACE;
1277 * ^, $, nul terminator characters.
1279 *replacedp = 1;
1280 len = (p - *ptrnp) * 2 + (nspaces + 2) * sizeof(CSCOPE_RE_SPACE) + 3;
1281 GET_SPACE_RET(sp, bp, blen, len);
1283 p = *ptrnp;
1284 t = bp;
1286 *t++ = '^';
1287 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1288 t += sizeof(CSCOPE_RE_SPACE) - 1;
1290 for (len = *plenp; len > 0; ++p, --len)
1291 if (*p == ' ') {
1292 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1293 t += sizeof(CSCOPE_RE_SPACE) - 1;
1294 } else {
1295 if (strchr("\\^.[]$*+?()|{}", *p))
1296 *t++ = '\\';
1297 *t++ = *p;
1300 memcpy(t, CSCOPE_RE_SPACE, sizeof(CSCOPE_RE_SPACE) - 1);
1301 t += sizeof(CSCOPE_RE_SPACE) - 1;
1302 *t++ = '$';
1304 *ptrnp = bp;
1305 *plenp = t - bp;
1306 return (0);
1310 * re_error --
1311 * Report a regular expression error.
1313 * PUBLIC: void re_error __P((SCR *, int, regex_t *));
1315 void
1316 re_error(sp, errcode, preg)
1317 SCR *sp;
1318 int errcode;
1319 regex_t *preg;
1321 size_t s;
1322 char *oe;
1324 s = regerror(errcode, preg, "", 0);
1325 if ((oe = malloc(s)) == NULL)
1326 msgq(sp, M_SYSERR, NULL);
1327 else {
1328 (void)regerror(errcode, preg, oe, s);
1329 msgq(sp, M_ERR, "RE error: %s", oe);
1330 free(oe);
1335 * re_sub --
1336 * Do the substitution for a regular expression.
1338 static int
1339 re_sub(sp, ip, lbp, lbclenp, lblenp, match)
1340 SCR *sp;
1341 char *ip; /* Input line. */
1342 char **lbp;
1343 size_t *lbclenp, *lblenp;
1344 regmatch_t match[10];
1346 enum { C_NOTSET, C_LOWER, C_ONELOWER, C_ONEUPPER, C_UPPER } conv;
1347 size_t lbclen, lblen; /* Local copies. */
1348 size_t mlen; /* Match length. */
1349 size_t rpl; /* Remaining replacement length. */
1350 char *rp; /* Replacement pointer. */
1351 int ch;
1352 int no; /* Match replacement offset. */
1353 char *p, *t; /* Buffer pointers. */
1354 char *lb; /* Local copies. */
1356 lb = *lbp; /* Get local copies. */
1357 lbclen = *lbclenp;
1358 lblen = *lblenp;
1361 * QUOTING NOTE:
1363 * There are some special sequences that vi provides in the
1364 * replacement patterns.
1365 * & string the RE matched (\& if nomagic set)
1366 * \# n-th regular subexpression
1367 * \E end \U, \L conversion
1368 * \e end \U, \L conversion
1369 * \l convert the next character to lower-case
1370 * \L convert to lower-case, until \E, \e, or end of replacement
1371 * \u convert the next character to upper-case
1372 * \U convert to upper-case, until \E, \e, or end of replacement
1374 * Otherwise, since this is the lowest level of replacement, discard
1375 * all escaping characters. This (hopefully) matches historic practice.
1377 #define OUTCH(ch, nltrans) { \
1378 CHAR_T __ch = (ch); \
1379 u_int __value = KEY_VAL(sp, __ch); \
1380 if (nltrans && (__value == K_CR || __value == K_NL)) { \
1381 NEEDNEWLINE(sp); \
1382 sp->newl[sp->newl_cnt++] = lbclen; \
1383 } else if (conv != C_NOTSET) { \
1384 switch (conv) { \
1385 case C_ONELOWER: \
1386 conv = C_NOTSET; \
1387 /* FALLTHROUGH */ \
1388 case C_LOWER: \
1389 if (isupper(__ch)) \
1390 __ch = tolower(__ch); \
1391 break; \
1392 case C_ONEUPPER: \
1393 conv = C_NOTSET; \
1394 /* FALLTHROUGH */ \
1395 case C_UPPER: \
1396 if (islower(__ch)) \
1397 __ch = toupper(__ch); \
1398 break; \
1399 default: \
1400 abort(); \
1403 NEEDSP(sp, 1, p); \
1404 *p++ = __ch; \
1405 ++lbclen; \
1407 conv = C_NOTSET;
1408 for (rp = sp->repl, rpl = sp->repl_len, p = lb + lbclen; rpl--;) {
1409 switch (ch = *rp++) {
1410 case '&':
1411 if (O_ISSET(sp, O_MAGIC)) {
1412 no = 0;
1413 goto subzero;
1415 break;
1416 case '\\':
1417 if (rpl == 0)
1418 break;
1419 --rpl;
1420 switch (ch = *rp) {
1421 case '&':
1422 ++rp;
1423 if (!O_ISSET(sp, O_MAGIC)) {
1424 no = 0;
1425 goto subzero;
1427 break;
1428 case '0': case '1': case '2': case '3': case '4':
1429 case '5': case '6': case '7': case '8': case '9':
1430 no = *rp++ - '0';
1431 subzero: if (match[no].rm_so == -1 ||
1432 match[no].rm_eo == -1)
1433 break;
1434 mlen = match[no].rm_eo - match[no].rm_so;
1435 for (t = ip + match[no].rm_so; mlen--; ++t)
1436 OUTCH(*t, 0);
1437 continue;
1438 case 'e':
1439 case 'E':
1440 ++rp;
1441 conv = C_NOTSET;
1442 continue;
1443 case 'l':
1444 ++rp;
1445 conv = C_ONELOWER;
1446 continue;
1447 case 'L':
1448 ++rp;
1449 conv = C_LOWER;
1450 continue;
1451 case 'u':
1452 ++rp;
1453 conv = C_ONEUPPER;
1454 continue;
1455 case 'U':
1456 ++rp;
1457 conv = C_UPPER;
1458 continue;
1459 default:
1460 ++rp;
1461 break;
1464 OUTCH(ch, 1);
1467 *lbp = lb; /* Update caller's information. */
1468 *lbclenp = lbclen;
1469 *lblenp = lblen;
1470 return (0);