2 * Copyright (c) 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * %sccs.include.redist.c%
9 static char sccsid
[] = "$Id: ex_subst.c,v 8.31 1994/01/02 17:54:08 bostic Exp $ (Berkeley) $Date: 1994/01/02 17:54:08 $";
12 #include <sys/types.h>
22 #define SUB_FIRST 0x01 /* The 'r' flag isn't reasonable. */
23 #define SUB_MUSTSETR 0x02 /* The 'r' flag is required. */
25 static int checkmatchsize
__P((SCR
*, regex_t
*));
26 static inline int regsub
__P((SCR
*,
27 char *, char **, size_t *, size_t *));
28 static int substitute
__P((SCR
*, EXF
*,
29 EXCMDARG
*, char *, regex_t
*, u_int
));
33 * [line [,line]] s[ubstitute] [[/;]pat[/;]/repl[/;] [cgr] [count] [#lp]]
35 * Substitute on lines matching a pattern.
38 ex_substitute(sp
, ep
, cmdp
)
46 int delim
, eval
, reflags
, replaced
;
47 char *bp
, *ptrn
, *rep
, *p
, *t
;
50 * Skip leading white space.
53 * Historic vi allowed any non-alphanumeric to serve as the
54 * substitution command delimiter.
57 * If the arguments are empty, it's the same as &, i.e. we
58 * repeat the last substitution.
60 for (p
= cmdp
->argv
[0]->bp
,
61 len
= cmdp
->argv
[0]->len
; len
> 0; --len
, ++p
) {
66 return (ex_subagain(sp
, ep
, cmdp
));
69 return (substitute(sp
, ep
,
70 cmdp
, p
, &sp
->subre
, SUB_MUSTSETR
));
73 * Get the pattern string, toss escaped characters.
76 * Historic vi accepted any of the following forms:
78 * :s/abc/def/ change "abc" to "def"
79 * :s/abc/def change "abc" to "def"
80 * :s/abc/ delete "abc"
85 * Only toss an escape character if it escapes a delimiter.
86 * This means that "s/A/\\\\f" replaces "A" with "\\f". It
87 * would be nice to be more regular, i.e. for each layer of
88 * escaping a single escape character is removed, but that's
89 * not how the historic vi worked.
91 for (ptrn
= t
= p
;;) {
92 if (p
[0] == '\0' || p
[0] == delim
) {
97 * Nul terminate the pattern string -- it's passed
98 * to regcomp which doesn't understand anything else.
103 if (p
[0] == '\\' && p
[1] == delim
)
108 /* If the pattern string is empty, use the last one. */
110 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
112 "No previous regular expression.");
120 if (O_ISSET(sp
, O_EXTENDED
))
121 reflags
|= REG_EXTENDED
;
122 if (O_ISSET(sp
, O_IGNORECASE
))
123 reflags
|= REG_ICASE
;
125 /* Convert vi-style RE's to POSIX 1003.2 RE's. */
126 if (re_conv(sp
, &ptrn
, &replaced
))
129 /* Compile the RE. */
130 eval
= regcomp(&lre
, (char *)ptrn
, reflags
);
132 /* Free up any allocated memory. */
134 FREE_SPACE(sp
, ptrn
, 0);
137 re_error(sp
, eval
, &lre
);
145 * Historic practice is that substitutes set the search
146 * direction as well as both substitute and search RE's.
148 sp
->searchdir
= FORWARD
;
150 F_SET(sp
, S_SRE_SET
);
152 F_SET(sp
, S_SUBRE_SET
);
159 * Get the replacement string.
161 * The special character ~ (\~ if O_MAGIC not set) inserts the
162 * previous replacement string into this replacement string.
164 * The special character & (\& if O_MAGIC not set) matches the
165 * entire RE. No handling of & is required here, it's done by
170 * Only toss an escape character if it escapes a delimiter or
171 * an escape character, or if O_MAGIC is set and it escapes a
175 if (sp
->repl
!= NULL
)
176 FREE(sp
->repl
, sp
->repl_len
);
181 * Count ~'s to figure out how much space we need. We could
182 * special case nonexistent last patterns or whether or not
183 * O_MAGIC is set, but it's probably not worth the effort.
185 for (rep
= p
, len
= 0;
186 p
[0] != '\0' && p
[0] != delim
; ++p
, ++len
)
189 GET_SPACE_RET(sp
, bp
, blen
, len
);
190 for (t
= bp
, len
= 0, p
= rep
;;) {
191 if (p
[0] == '\0' || p
[0] == delim
) {
197 if (p
[1] == '\\' || p
[1] == delim
)
199 else if (p
[1] == '~') {
201 if (!O_ISSET(sp
, O_MAGIC
))
204 } else if (p
[0] == '~' && O_ISSET(sp
, O_MAGIC
)) {
206 memmove(t
, sp
->repl
, sp
->repl_len
);
214 if (sp
->repl
!= NULL
)
215 FREE(sp
->repl
, sp
->repl_len
);
216 if ((sp
->repl
= malloc(len
)) == NULL
) {
217 msgq(sp
, M_SYSERR
, NULL
);
218 FREE_SPACE(sp
, bp
, blen
);
221 memmove(sp
->repl
, bp
, len
);
223 FREE_SPACE(sp
, bp
, blen
);
226 if (checkmatchsize(sp
, &sp
->subre
))
228 return (substitute(sp
, ep
, cmdp
, p
, re
, flags
));
233 * [line [,line]] & [cgr] [count] [#lp]]
235 * Substitute using the last substitute RE and replacement pattern.
238 ex_subagain(sp
, ep
, cmdp
)
243 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
244 msgq(sp
, M_ERR
, "No previous regular expression.");
247 return (substitute(sp
, ep
, cmdp
, cmdp
->argv
[0]->bp
, &sp
->subre
, 0));
252 * [line [,line]] ~ [cgr] [count] [#lp]]
254 * Substitute using the last RE and last substitute replacement pattern.
257 ex_subtilde(sp
, ep
, cmdp
)
262 if (!F_ISSET(sp
, S_SRE_SET
)) {
263 msgq(sp
, M_ERR
, "No previous regular expression.");
266 return (substitute(sp
, ep
, cmdp
, cmdp
->argv
[0]->bp
, &sp
->sre
, 0));
270 * The nasty part of the substitution is what happens when the replacement
271 * string contains newlines. It's a bit tricky -- consider the information
272 * that has to be retained for "s/f\(o\)o/^M\1^M\1/". The solution here is
273 * to build a set of newline offsets which we use to break the line up later,
274 * when the replacement is done. Don't change it unless you're pretty damned
277 #define NEEDNEWLINE(sp) { \
278 if (sp->newl_len == sp->newl_cnt) { \
279 sp->newl_len += 25; \
280 REALLOC(sp, sp->newl, size_t *, \
281 sp->newl_len * sizeof(size_t)); \
282 if (sp->newl == NULL) { \
289 #define BUILD(sp, l, len) { \
290 if (lbclen + (len) > lblen) { \
291 lblen += MAX(lbclen + (len), 256); \
292 REALLOC(sp, lb, char *, lblen); \
298 memmove(lb + lbclen, l, len); \
302 #define NEEDSP(sp, len, pnt) { \
303 if (lbclen + (len) > lblen) { \
304 lblen += MAX(lbclen + (len), 256); \
305 REALLOC(sp, lb, char *, lblen); \
316 * Do the substitution. This stuff is *really* tricky. There are
317 * lots of special cases, and general nastiness. Don't mess with it
318 * unless you're pretty confident.
321 substitute(sp
, ep
, cmdp
, s
, re
, flags
)
331 size_t blen
, cnt
, last
, lbclen
, lblen
, len
, llen
, offset
, saved_offset
;
332 int didsub
, do_eol_match
;
333 int eflags
, empty_ok
, eval
, linechanged
, matched
, quit
;
334 int cflag
, gflag
, lflag
, nflag
, pflag
, rflag
;
338 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
339 * it only displayed the last change. I'd disallow them, but they are
340 * useful in combination with the [v]global commands. In the current
341 * model the problem is combining them with the 'c' flag -- the screen
342 * would have to flip back and forth between the confirm screen and the
343 * ex print screen, which would be pretty awful. We do display all
344 * changes, though, for what that's worth.
347 * Historic vi was fairly strict about the order of "options", the
348 * count, and "flags". I'm somewhat fuzzy on the difference between
349 * options and flags, anyway, so this is a simpler approach, and we
350 * just take it them in whatever order the user gives them. (The ex
351 * usage statement doesn't reflect this.)
353 cflag
= gflag
= lflag
= nflag
= pflag
= rflag
= 0;
354 for (lno
= OOBLNO
; *s
!= '\0'; ++s
)
359 case '0': case '1': case '2': case '3': case '4':
360 case '5': case '6': case '7': case '8': case '9':
364 lno
= strtoul(s
, &s
, 10);
365 if (*s
== '\0') /* Loop increment correction. */
367 if (errno
== ERANGE
) {
369 msgq(sp
, M_ERR
, "Count overflow.");
370 else if (lno
== LONG_MIN
)
371 msgq(sp
, M_ERR
, "Count underflow.");
373 msgq(sp
, M_SYSERR
, NULL
);
377 * In historic vi, the count was inclusive from the
380 cmdp
->addr1
.lno
= cmdp
->addr2
.lno
;
381 cmdp
->addr2
.lno
+= lno
- 1;
399 if (LF_ISSET(SUB_FIRST
)) {
401 "Regular expression specified; r flag meaningless.");
404 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
406 "No previous regular expression.");
415 if (*s
!= '\0' || !rflag
&& LF_ISSET(SUB_MUSTSETR
)) {
416 usage
: msgq(sp
, M_ERR
, "Usage: %s", cmdp
->cmd
->usage
);
420 if (IN_VI_MODE(sp
) && cflag
&& (lflag
|| nflag
|| pflag
)) {
422 "The #, l and p flags may not be combined with the c flag in vi mode.");
427 * bp: if interactive, line cache
428 * blen: if interactive, line cache length
429 * lb: build buffer pointer.
430 * lbclen: current length of built buffer.
431 * lblen; length of build buffer.
434 blen
= lbclen
= lblen
= 0;
436 /* For each line... */
437 for (matched
= quit
= 0, lno
= cmdp
->addr1
.lno
,
438 elno
= cmdp
->addr2
.lno
; !quit
&& lno
<= elno
; ++lno
) {
441 if ((s
= file_gline(sp
, ep
, lno
, &llen
)) == NULL
) {
442 GETLINE_ERR(sp
, lno
);
447 * Make a local copy if doing confirmation -- when calling
448 * the confirm routine we're likely to lose the cached copy.
452 GET_SPACE_RET(sp
, bp
, blen
, llen
);
454 ADD_SPACE_RET(sp
, bp
, blen
, llen
);
455 memmove(bp
, s
, llen
);
459 /* Start searching from the beginning. */
463 /* Reset the build buffer offset. */
466 /* Reset empty match flag. */
470 * We don't want to have to do a setline if the line didn't
471 * change -- keep track of whether or not this line changed.
472 * If doing confirmations, don't want to keep setting the
473 * line if change is refused -- keep track of substitutions.
475 didsub
= linechanged
= 0;
477 /* New line, do an EOL match. */
480 /* It's not nul terminated, but we pretend it is. */
481 eflags
= REG_STARTEND
;
484 * The search area is from s + offset to the EOL.
486 * Generally, sp->match[0].rm_so is the offset of the start
487 * of the match from the start of the search, and offset is
488 * the offset of the start of the last search.
490 nextmatch
: sp
->match
[0].rm_so
= 0;
491 sp
->match
[0].rm_eo
= len
;
493 /* Get the next match. */
495 (char *)s
+ offset
, re
->re_nsub
+ 1, sp
->match
, eflags
);
498 * There wasn't a match or if there was an error, deal with
499 * it. If there was a previous match in this line, resolve
500 * the changes into the database. Otherwise, just move on.
502 if (eval
== REG_NOMATCH
)
505 re_error(sp
, eval
, re
);
510 /* Only the first search can match an anchored expression. */
511 eflags
|= REG_NOTBOL
;
515 * It's possible to match 0-length strings -- for example, the
516 * command s;a*;X;, when matched against the string "aabb" will
517 * result in "XbXbX", i.e. the matches are "aa", the space
518 * between the b's and the space between the b's and the end of
519 * the string. There is a similar space between the beginning
520 * of the string and the a's. The rule that we use (because vi
521 * historically used it) is that any 0-length match, occurring
522 * immediately after a match, is ignored. Otherwise, the above
523 * example would have resulted in "XXbXbX". Another example is
524 * incorrectly using " *" to replace groups of spaces with one
527 * The way we do this is that if we just had a successful match,
528 * the starting offset does not skip characters, and the match
529 * is empty, ignore the match and move forward. If there's no
530 * more characters in the string, we were attempting to match
531 * after the last character, so quit.
534 sp
->match
[0].rm_so
== 0 && sp
->match
[0].rm_eo
== 0) {
538 BUILD(sp
, s
+ offset
, 1)
544 /* Confirm change. */
547 * Set the cursor position for confirmation. Note,
548 * if we matched on a '$', the cursor may be past
552 * We may want to "fix" this in the confirm routine,
553 * if the confirm routine should be able to display
556 from
.lno
= to
.lno
= lno
;
557 from
.cno
= sp
->match
[0].rm_so
+ offset
;
558 to
.cno
= sp
->match
[0].rm_eo
;
560 from
.cno
= to
.cno
= 0;
564 if (from
.cno
>= llen
)
567 switch (sp
->s_confirm(sp
, ep
, &from
, &to
)) {
572 BUILD(sp
, s
+offset
, sp
->match
[0].rm_eo
);
575 /* Set the quit flag. */
578 /* If interruptible, pass the info back. */
579 if (F_ISSET(sp
, S_INTERRUPTIBLE
))
580 F_SET(sp
, S_INTERRUPTED
);
583 * If any changes, resolve them, otherwise
584 * return to the main loop.
590 /* Copy the bytes before the match into the build buffer. */
591 BUILD(sp
, s
+ offset
, sp
->match
[0].rm_so
);
594 * Cursor moves to last line changed, unless doing confirm,
595 * in which case don't move it.
598 * Historic vi just put the cursor on the first non-blank
599 * of the last line changed. This might be better.
603 sp
->cno
= sp
->match
[0].rm_so
+ offset
;
606 /* Substitute the matching bytes. */
608 if (regsub(sp
, s
+ offset
, &lb
, &lbclen
, &lblen
))
611 /* Set the change flag so we know this line was modified. */
614 /* Move past the matched bytes. */
615 skip
: offset
+= sp
->match
[0].rm_eo
;
616 len
-= sp
->match
[0].rm_eo
;
618 /* A match cannot be followed by an empty pattern. */
622 * If doing a global change with confirmation, we have to
623 * update the screen. The basic idea is to store the line
624 * so the screen update routines can find it, and restart.
626 if (didsub
&& cflag
&& gflag
) {
628 * The new search offset will be the end of the
631 saved_offset
= lbclen
;
633 /* Copy the rest of the line. */
635 BUILD(sp
, s
+ offset
, len
)
637 /* Set the new offset. */
638 offset
= saved_offset
;
640 /* Store inserted lines, adjusting the build buffer. */
644 cnt
< sp
->newl_cnt
; ++cnt
, ++lno
, ++elno
) {
645 if (file_iline(sp
, ep
, lno
,
646 lb
+ last
, sp
->newl
[cnt
] - last
))
648 last
= sp
->newl
[cnt
] + 1;
649 ++sp
->rptlines
[L_ADDED
];
656 /* Store and retrieve the line. */
657 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
659 if ((s
= file_gline(sp
, ep
, lno
, &llen
)) == NULL
) {
660 GETLINE_ERR(sp
, lno
);
663 ADD_SPACE_RET(sp
, bp
, blen
, llen
)
664 memmove(bp
, s
, llen
);
668 /* Restart the build. */
670 BUILD(sp
, s
, offset
);
673 * If we haven't already done the after-the-string
674 * match, do one. Set REG_NOTEOL so the '$' pattern
681 eflags
|= REG_NOTEOL
;
689 * If at the end of the string, do a test for the after
690 * the string match. Set REG_NOTEOL so the '$' pattern
693 if (gflag
&& do_eol_match
) {
696 eflags
|= REG_NOTEOL
;
701 endmatch
: if (!linechanged
)
704 /* Copy any remaining bytes into the build buffer. */
706 BUILD(sp
, s
+ offset
, len
)
708 /* Store inserted lines, adjusting the build buffer. */
712 cnt
< sp
->newl_cnt
; ++cnt
, ++lno
, ++elno
) {
713 if (file_iline(sp
, ep
,
714 lno
, lb
+ last
, sp
->newl
[cnt
] - last
))
716 last
= sp
->newl
[cnt
] + 1;
717 ++sp
->rptlines
[L_ADDED
];
723 /* Store the changed line. */
724 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
727 /* Update changed line counter. */
728 ++sp
->rptlines
[L_CHANGED
];
730 /* Display as necessary. */
731 if (lflag
|| nflag
|| pflag
) {
732 from
.lno
= to
.lno
= lno
;
733 from
.cno
= to
.cno
= 0;
735 ex_print(sp
, ep
, &from
, &to
, E_F_LIST
);
737 ex_print(sp
, ep
, &from
, &to
, E_F_HASH
);
739 ex_print(sp
, ep
, &from
, &to
, E_F_PRINT
);
744 * If not in a global command, and nothing matched, say so.
745 * Else, if none of the lines displayed, put something up.
748 if (!F_ISSET(sp
, S_GLOBAL
))
749 msgq(sp
, M_INFO
, "No match found.");
750 } else if (!lflag
&& !nflag
&& !pflag
)
751 F_SET(EXP(sp
), EX_AUTOPRINT
);
754 FREE_SPACE(sp
, bp
, blen
);
758 ret1
: FREE_SPACE(sp
, bp
, blen
);
764 * Do the substitution for a regular expression.
767 regsub(sp
, ip
, lbp
, lbclenp
, lblenp
)
769 char *ip
; /* Input line. */
771 size_t *lbclenp
, *lblenp
;
773 enum { C_NOTSET
, C_LOWER
, C_ONELOWER
, C_ONEUPPER
, C_UPPER
} conv
;
774 size_t lbclen
, lblen
; /* Local copies. */
775 size_t mlen
; /* Match length. */
776 size_t rpl
; /* Remaining replacement length. */
777 char *rp
; /* Replacement pointer. */
779 int no
; /* Match replacement offset. */
780 char *p
, *t
; /* Buffer pointers. */
781 char *lb
; /* Local copies. */
783 lb
= *lbp
; /* Get local copies. */
790 * There are some special sequences that vi provides in the
791 * replacement patterns.
792 * & string the RE matched (\& if nomagic set)
793 * \# n-th regular subexpression
794 * \E end \U, \L conversion
795 * \e end \U, \L conversion
796 * \l convert the next character to lower-case
797 * \L convert to lower-case, until \E, \e, or end of replacement
798 * \u convert the next character to upper-case
799 * \U convert to upper-case, until \E, \e, or end of replacement
801 * Otherwise, since this is the lowest level of replacement, discard
802 * all escape characters. This (hopefully) follows historic practice.
804 #define ADDCH(ch) { \
805 CHAR_T __ch = (ch); \
806 u_int __value = term_key_val(sp, __ch); \
807 if (__value == K_CR || __value == K_NL) { \
809 sp->newl[sp->newl_cnt++] = lbclen; \
810 } else if (conv != C_NOTSET) { \
817 __ch = tolower(__ch); \
824 __ch = toupper(__ch); \
835 for (rp
= sp
->repl
, rpl
= sp
->repl_len
, p
= lb
+ lbclen
; rpl
--;) {
836 switch (ch
= *rp
++) {
838 if (O_ISSET(sp
, O_MAGIC
)) {
849 if (!O_ISSET(sp
, O_MAGIC
)) {
855 case '0': case '1': case '2': case '3': case '4':
856 case '5': case '6': case '7': case '8': case '9':
858 subzero
: if (sp
->match
[no
].rm_so
== -1 ||
859 sp
->match
[no
].rm_eo
== -1)
862 sp
->match
[no
].rm_eo
- sp
->match
[no
].rm_so
;
863 for (t
= ip
+ sp
->match
[no
].rm_so
; mlen
--; ++t
)
895 *lbp
= lb
; /* Update caller's information. */
902 checkmatchsize(sp
, re
)
906 /* Build nsub array as necessary. */
907 if (sp
->matchsize
< re
->re_nsub
+ 1) {
908 sp
->matchsize
= re
->re_nsub
+ 1;
909 REALLOC(sp
, sp
->match
,
910 regmatch_t
*, sp
->matchsize
* sizeof(regmatch_t
));
911 if (sp
->match
== NULL
) {