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.29 1993/12/23 16:10:22 bostic Exp $ (Berkeley) $Date: 1993/12/23 16:10:22 $";
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 TRACE(sp, "lblen = %u\n", lblen); \
306 REALLOC(sp, lb, char *, lblen); \
317 * Do the substitution. This stuff is *really* tricky. There are
318 * lots of special cases, and general nastiness. Don't mess with it
319 * unless you're pretty confident.
322 substitute(sp
, ep
, cmdp
, s
, re
, flags
)
332 size_t blen
, cnt
, last
, lbclen
, lblen
, len
, llen
, offset
, saved_offset
;
333 int didsub
, do_eol_match
;
334 int eflags
, empty_ok
, eval
, linechanged
, matched
, quit
;
335 int cflag
, gflag
, lflag
, nflag
, pflag
, rflag
;
339 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
340 * it only displayed the last change. I'd disallow them, but they are
341 * useful in combination with the [v]global commands. In the current
342 * model the problem is combining them with the 'c' flag -- the screen
343 * would have to flip back and forth between the confirm screen and the
344 * ex print screen, which would be pretty awful. We do display all
345 * changes, though, for what that's worth.
348 * Historic vi was fairly strict about the order of "options", the
349 * count, and "flags". I'm somewhat fuzzy on the difference between
350 * options and flags, anyway, so this is a simpler approach, and we
351 * just take it them in whatever order the user gives them. (The ex
352 * usage statement doesn't reflect this.)
354 cflag
= gflag
= lflag
= nflag
= pflag
= rflag
= 0;
355 for (lno
= OOBLNO
; *s
!= '\0'; ++s
)
360 case '0': case '1': case '2': case '3': case '4':
361 case '5': case '6': case '7': case '8': case '9':
365 lno
= strtoul(s
, &s
, 10);
366 if (*s
== '\0') /* Loop increment correction. */
368 if (errno
== ERANGE
) {
370 msgq(sp
, M_ERR
, "Count overflow.");
371 else if (lno
== LONG_MIN
)
372 msgq(sp
, M_ERR
, "Count underflow.");
374 msgq(sp
, M_SYSERR
, NULL
);
378 * In historic vi, the count was inclusive from the
381 cmdp
->addr1
.lno
= cmdp
->addr2
.lno
;
382 cmdp
->addr2
.lno
+= lno
- 1;
400 if (LF_ISSET(SUB_FIRST
)) {
402 "Regular expression specified; r flag meaningless.");
405 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
407 "No previous regular expression.");
416 if (*s
!= '\0' || !rflag
&& LF_ISSET(SUB_MUSTSETR
)) {
417 usage
: msgq(sp
, M_ERR
, "Usage: %s", cmdp
->cmd
->usage
);
421 if (IN_VI_MODE(sp
) && cflag
&& (lflag
|| nflag
|| pflag
)) {
423 "The #, l and p flags may not be combined with the c flag in vi mode.");
428 * bp: if interactive, line cache
429 * blen: if interactive, line cache length
430 * lb: build buffer pointer.
431 * lbclen: current length of built buffer.
432 * lblen; length of build buffer.
435 blen
= lbclen
= lblen
= 0;
437 /* For each line... */
438 for (matched
= quit
= 0, lno
= cmdp
->addr1
.lno
,
439 elno
= cmdp
->addr2
.lno
; !quit
&& lno
<= elno
; ++lno
) {
442 if ((s
= file_gline(sp
, ep
, lno
, &llen
)) == NULL
) {
443 GETLINE_ERR(sp
, lno
);
448 * Make a local copy if doing confirmation -- when calling
449 * the confirm routine we're likely to lose the cached copy.
453 GET_SPACE_RET(sp
, bp
, blen
, llen
);
455 ADD_SPACE_RET(sp
, bp
, blen
, llen
);
456 memmove(bp
, s
, llen
);
460 /* Start searching from the beginning. */
464 /* Reset the build buffer offset. */
467 /* Reset empty match flag. */
471 * We don't want to have to do a setline if the line didn't
472 * change -- keep track of whether or not this line changed.
473 * If doing confirmations, don't want to keep setting the
474 * line if change is refused -- keep track of substitutions.
476 didsub
= linechanged
= 0;
478 /* New line, do an EOL match. */
481 /* It's not nul terminated, but we pretend it is. */
482 eflags
= REG_STARTEND
;
485 * The search area is from s + offset to the EOL.
487 * Generally, sp->match[0].rm_so is the offset of the start
488 * of the match from the start of the search, and offset is
489 * the offset of the start of the last search.
491 nextmatch
: sp
->match
[0].rm_so
= 0;
492 sp
->match
[0].rm_eo
= len
;
494 /* Get the next match. */
496 (char *)s
+ offset
, re
->re_nsub
+ 1, sp
->match
, eflags
);
499 * There wasn't a match or if there was an error, deal with
500 * it. If there was a previous match in this line, resolve
501 * the changes into the database. Otherwise, just move on.
503 if (eval
== REG_NOMATCH
)
506 re_error(sp
, eval
, re
);
511 /* Only the first search can match an anchored expression. */
512 eflags
|= REG_NOTBOL
;
516 * It's possible to match 0-length strings -- for example, the
517 * command s;a*;X;, when matched against the string "aabb" will
518 * result in "XbXbX", i.e. the matches are "aa", the space
519 * between the b's and the space between the b's and the end of
520 * the string. There is a similar space between the beginning
521 * of the string and the a's. The rule that we use (because vi
522 * historically used it) is that any 0-length match, occurring
523 * immediately after a match, is ignored. Otherwise, the above
524 * example would have resulted in "XXbXbX". Another example is
525 * incorrectly using " *" to replace groups of spaces with one
528 * The way we do this is that if we just had a successful match,
529 * the starting offset does not skip characters, and the match
530 * is empty, ignore the match and move forward. If there's no
531 * more characters in the string, we were attempting to match
532 * after the last character, so quit.
535 sp
->match
[0].rm_so
== 0 && sp
->match
[0].rm_eo
== 0) {
539 BUILD(sp
, s
+ offset
, 1)
545 /* Confirm change. */
548 * Set the cursor position for confirmation. Note,
549 * if we matched on a '$', the cursor may be past
553 * We may want to "fix" this in the confirm routine,
554 * if the confirm routine should be able to display
557 from
.lno
= to
.lno
= lno
;
558 from
.cno
= sp
->match
[0].rm_so
+ offset
;
559 to
.cno
= sp
->match
[0].rm_eo
;
561 from
.cno
= to
.cno
= 0;
565 if (from
.cno
>= llen
)
568 switch (sp
->s_confirm(sp
, ep
, &from
, &to
)) {
573 BUILD(sp
, s
+offset
, sp
->match
[0].rm_eo
);
576 /* Set the quit flag. */
579 /* If interruptible, pass the info back. */
580 if (F_ISSET(sp
, S_INTERRUPTIBLE
))
581 F_SET(sp
, S_INTERRUPTED
);
584 * If any changes, resolve them, otherwise
585 * return to the main loop.
591 /* Copy the bytes before the match into the build buffer. */
592 BUILD(sp
, s
+ offset
, sp
->match
[0].rm_so
);
595 * Cursor moves to last line changed, unless doing confirm,
596 * in which case don't move it.
599 * Historic vi just put the cursor on the first non-blank
600 * of the last line changed. This might be better.
604 sp
->cno
= sp
->match
[0].rm_so
+ offset
;
607 /* Substitute the matching bytes. */
609 if (regsub(sp
, s
+ offset
, &lb
, &lbclen
, &lblen
))
612 /* Set the change flag so we know this line was modified. */
615 /* Move past the matched bytes. */
616 skip
: offset
+= sp
->match
[0].rm_eo
;
617 len
-= sp
->match
[0].rm_eo
;
619 /* A match cannot be followed by an empty pattern. */
623 * If doing a global change with confirmation, we have to
624 * update the screen. The basic idea is to store the line
625 * so the screen update routines can find it, and restart.
627 if (didsub
&& cflag
&& gflag
) {
629 * The new search offset will be the end of the
632 saved_offset
= lbclen
;
634 /* Copy the rest of the line. */
636 BUILD(sp
, s
+ offset
, len
)
638 /* Set the new offset. */
639 offset
= saved_offset
;
641 /* Store inserted lines, adjusting the build buffer. */
645 cnt
< sp
->newl_cnt
; ++cnt
, ++lno
, ++elno
) {
646 if (file_iline(sp
, ep
, lno
,
647 lb
+ last
, sp
->newl
[cnt
] - last
))
649 last
= sp
->newl
[cnt
] + 1;
650 ++sp
->rptlines
[L_ADDED
];
657 /* Store and retrieve the line. */
658 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
660 if ((s
= file_gline(sp
, ep
, lno
, &llen
)) == NULL
) {
661 GETLINE_ERR(sp
, lno
);
664 ADD_SPACE_RET(sp
, bp
, blen
, llen
)
665 memmove(bp
, s
, llen
);
669 /* Restart the build. */
671 BUILD(sp
, s
, offset
);
674 * If we haven't already done the after-the-string
675 * match, do one. Set REG_NOTEOL so the '$' pattern
682 eflags
|= REG_NOTEOL
;
690 * If at the end of the string, do a test for the after
691 * the string match. Set REG_NOTEOL so the '$' pattern
694 if (gflag
&& do_eol_match
) {
697 eflags
|= REG_NOTEOL
;
702 endmatch
: if (!linechanged
)
705 /* Copy any remaining bytes into the build buffer. */
707 BUILD(sp
, s
+ offset
, len
)
709 /* Store inserted lines, adjusting the build buffer. */
713 cnt
< sp
->newl_cnt
; ++cnt
, ++lno
, ++elno
) {
714 if (file_iline(sp
, ep
,
715 lno
, lb
+ last
, sp
->newl
[cnt
] - last
))
717 last
= sp
->newl
[cnt
] + 1;
718 ++sp
->rptlines
[L_ADDED
];
724 /* Store the changed line. */
725 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
728 /* Update changed line counter. */
729 ++sp
->rptlines
[L_CHANGED
];
731 /* Display as necessary. */
732 if (lflag
|| nflag
|| pflag
) {
733 from
.lno
= to
.lno
= lno
;
734 from
.cno
= to
.cno
= 0;
736 ex_print(sp
, ep
, &from
, &to
, E_F_LIST
);
738 ex_print(sp
, ep
, &from
, &to
, E_F_HASH
);
740 ex_print(sp
, ep
, &from
, &to
, E_F_PRINT
);
745 * If not in a global command, and nothing matched, say so.
746 * Else, if none of the lines displayed, put something up.
749 if (!F_ISSET(sp
, S_GLOBAL
))
750 msgq(sp
, M_INFO
, "No match found.");
751 } else if (!lflag
&& !nflag
&& !pflag
)
752 F_SET(sp
, S_AUTOPRINT
);
755 FREE_SPACE(sp
, bp
, blen
);
759 ret1
: FREE_SPACE(sp
, bp
, blen
);
765 * Do the substitution for a regular expression.
768 regsub(sp
, ip
, lbp
, lbclenp
, lblenp
)
770 char *ip
; /* Input line. */
772 size_t *lbclenp
, *lblenp
;
774 enum { C_NOTSET
, C_LOWER
, C_ONELOWER
, C_ONEUPPER
, C_UPPER
} conv
;
775 size_t lbclen
, lblen
; /* Local copies. */
776 size_t mlen
; /* Match length. */
777 size_t rpl
; /* Remaining replacement length. */
778 char *rp
; /* Replacement pointer. */
780 int no
; /* Match replacement offset. */
781 char *p
, *t
; /* Buffer pointers. */
782 char *lb
; /* Local copies. */
784 lb
= *lbp
; /* Get local copies. */
791 * There are some special sequences that vi provides in the
792 * replacement patterns.
793 * & string the RE matched (\& if nomagic set)
794 * \# n-th regular subexpression
795 * \E end \U, \L conversion
796 * \e end \U, \L conversion
797 * \l convert the next character to lower-case
798 * \L convert to lower-case, until \E, \e, or end of replacement
799 * \u convert the next character to upper-case
800 * \U convert to upper-case, until \E, \e, or end of replacement
802 * Otherwise, since this is the lowest level of replacement, discard
803 * all escape characters. This (hopefully) follows historic practice.
805 #define ADDCH(ch) { \
806 CHAR_T __ch = (ch); \
807 u_int __value = term_key_val(sp, __ch); \
808 if (__value == K_CR || __value == K_NL) { \
810 sp->newl[sp->newl_cnt++] = lbclen; \
811 } else if (conv != C_NOTSET) { \
818 __ch = tolower(__ch); \
825 __ch = toupper(__ch); \
836 for (rp
= sp
->repl
, rpl
= sp
->repl_len
, p
= lb
+ lbclen
; rpl
--;) {
837 switch (ch
= *rp
++) {
839 if (O_ISSET(sp
, O_MAGIC
)) {
850 if (!O_ISSET(sp
, O_MAGIC
)) {
856 case '0': case '1': case '2': case '3': case '4':
857 case '5': case '6': case '7': case '8': case '9':
859 subzero
: if (sp
->match
[no
].rm_so
== -1 ||
860 sp
->match
[no
].rm_eo
== -1)
863 sp
->match
[no
].rm_eo
- sp
->match
[no
].rm_so
;
864 for (t
= ip
+ sp
->match
[no
].rm_so
; mlen
--; ++t
)
896 *lbp
= lb
; /* Update caller's information. */
903 checkmatchsize(sp
, re
)
907 /* Build nsub array as necessary. */
908 if (sp
->matchsize
< re
->re_nsub
+ 1) {
909 sp
->matchsize
= re
->re_nsub
+ 1;
910 REALLOC(sp
, sp
->match
,
911 regmatch_t
*, sp
->matchsize
* sizeof(regmatch_t
));
912 if (sp
->match
== NULL
) {