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.26 1993/12/20 09:45:26 bostic Exp $ (Berkeley) $Date: 1993/12/20 09:45:26 $";
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
));
32 * [line [,line]] s[ubstitute] [[/;]pat[/;]/repl[/;] [cgr] [count] [#lp]]
34 * Substitute on lines matching a pattern.
37 ex_substitute(sp
, ep
, cmdp
)
45 int delim
, eval
, reflags
, replaced
;
46 char *bp
, *ptrn
, *rep
, *p
, *t
;
49 * Skip leading white space.
52 * Historic vi allowed any non-alphanumeric to serve as the
53 * substitution command delimiter.
56 * If the arguments are empty, it's the same as &, i.e. we
57 * repeat the last substitution.
59 for (p
= cmdp
->argv
[0]->bp
,
60 len
= cmdp
->argv
[0]->len
; len
> 0; --len
, ++p
) {
65 return (ex_subagain(sp
, ep
, cmdp
));
68 return (substitute(sp
, ep
,
69 cmdp
, p
, &sp
->subre
, SUB_MUSTSETR
));
72 * Get the pattern string, toss escaped characters.
75 * Historic vi accepted any of the following forms:
77 * :s/abc/def/ change "abc" to "def"
78 * :s/abc/def change "abc" to "def"
79 * :s/abc/ delete "abc"
84 * Only toss an escape character if it escapes a delimiter.
85 * This means that "s/A/\\\\f" replaces "A" with "\\f". It
86 * would be nice to be more regular, i.e. for each layer of
87 * escaping a single escape character is removed, but that's
88 * not how the historic vi worked.
90 for (ptrn
= t
= p
;;) {
91 if (p
[0] == '\0' || p
[0] == delim
) {
96 * Nul terminate the pattern string -- it's passed
97 * to regcomp which doesn't understand anything else.
102 if (p
[0] == '\\' && p
[1] == delim
)
107 /* If the pattern string is empty, use the last one. */
109 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
111 "No previous regular expression.");
119 if (O_ISSET(sp
, O_EXTENDED
))
120 reflags
|= REG_EXTENDED
;
121 if (O_ISSET(sp
, O_IGNORECASE
))
122 reflags
|= REG_ICASE
;
124 /* Convert vi-style RE's to POSIX 1003.2 RE's. */
125 if (re_conv(sp
, &ptrn
, &replaced
))
128 /* Compile the RE. */
129 eval
= regcomp(&lre
, (char *)ptrn
, reflags
);
131 /* Free up any allocated memory. */
133 FREE_SPACE(sp
, ptrn
, 0);
136 re_error(sp
, eval
, &lre
);
144 * Historic practice is that substitutes set the search
145 * direction as well as both substitute and search RE's.
147 sp
->searchdir
= FORWARD
;
149 F_SET(sp
, S_SRE_SET
);
151 F_SET(sp
, S_SUBRE_SET
);
158 * Get the replacement string.
160 * The special character ~ (\~ if O_MAGIC not set) inserts the
161 * previous replacement string into this replacement string.
163 * The special character & (\& if O_MAGIC not set) matches the
164 * entire RE. No handling of & is required here, it's done by
169 * Only toss an escape character if it escapes a delimiter or
170 * an escape character, or if O_MAGIC is set and it escapes a
174 if (sp
->repl
!= NULL
)
175 FREE(sp
->repl
, sp
->repl_len
);
180 * Count ~'s to figure out how much space we need. We could
181 * special case nonexistent last patterns or whether or not
182 * O_MAGIC is set, but it's probably not worth the effort.
184 for (rep
= p
, len
= 0;
185 p
[0] != '\0' && p
[0] != delim
; ++p
, ++len
)
188 GET_SPACE_RET(sp
, bp
, blen
, len
);
189 for (t
= bp
, len
= 0, p
= rep
;;) {
190 if (p
[0] == '\0' || p
[0] == delim
) {
196 if (p
[1] == '\\' || p
[1] == delim
)
198 else if (p
[1] == '~') {
200 if (!O_ISSET(sp
, O_MAGIC
))
203 } else if (p
[0] == '~' && O_ISSET(sp
, O_MAGIC
)) {
205 memmove(t
, sp
->repl
, sp
->repl_len
);
213 if (sp
->repl
!= NULL
)
214 FREE(sp
->repl
, sp
->repl_len
);
215 if ((sp
->repl
= malloc(len
)) == NULL
) {
216 msgq(sp
, M_SYSERR
, NULL
);
217 FREE_SPACE(sp
, bp
, blen
);
220 memmove(sp
->repl
, bp
, len
);
222 FREE_SPACE(sp
, bp
, blen
);
225 if (checkmatchsize(sp
, &sp
->subre
))
227 return (substitute(sp
, ep
, cmdp
, p
, re
, flags
));
232 * [line [,line]] & [cgr] [count] [#lp]]
234 * Substitute using the last substitute RE and replacement pattern.
237 ex_subagain(sp
, ep
, cmdp
)
242 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
243 msgq(sp
, M_ERR
, "No previous regular expression.");
246 return (substitute(sp
, ep
, cmdp
, cmdp
->argv
[0]->bp
, &sp
->subre
, 0));
251 * [line [,line]] ~ [cgr] [count] [#lp]]
253 * Substitute using the last RE and last substitute replacement pattern.
256 ex_subtilde(sp
, ep
, cmdp
)
261 if (!F_ISSET(sp
, S_SRE_SET
)) {
262 msgq(sp
, M_ERR
, "No previous regular expression.");
265 return (substitute(sp
, ep
, cmdp
, cmdp
->argv
[0]->bp
, &sp
->sre
, 0));
269 * The nasty part of the substitution is what happens when the replacement
270 * string contains newlines. It's a bit tricky -- consider the information
271 * that has to be retained for "s/f\(o\)o/^M\1^M\1/". The solution here is
272 * to build a set of newline offets which we use to break the line up later,
273 * when the replacement is done. Don't change it unless you're pretty damned
276 #define NEEDNEWLINE(sp) { \
277 if (sp->newl_len == sp->newl_cnt) { \
278 sp->newl_len += 25; \
279 REALLOC(sp, sp->newl, size_t *, \
280 sp->newl_len * sizeof(size_t)); \
281 if (sp->newl == NULL) { \
288 #define BUILD(sp, l, len) { \
289 if (lbclen + (len) > lblen) { \
290 lblen += MAX(lbclen + (len), 256); \
291 REALLOC(sp, lb, char *, lblen); \
297 memmove(lb + lbclen, l, len); \
301 #define NEEDSP(sp, len, pnt) { \
302 if (lbclen + (len) > lblen) { \
303 lblen += MAX(lbclen + (len), 256); \
304 REALLOC(sp, lb, char *, lblen); \
315 * Do the substitution. This stuff is *really* tricky. There are
316 * lots of special cases, and general nastiness. Don't mess with it
317 * unless you're pretty confident.
320 substitute(sp
, ep
, cmdp
, s
, re
, flags
)
329 recno_t elno
, lno
, lastline
;
330 size_t blen
, cnt
, last
, lbclen
, lblen
, len
, offset
;
331 int do_eol_match
, eflags
, empty_ok
, eval
, linechanged
, quit
;
332 int cflag
, gflag
, lflag
, nflag
, pflag
, rflag
;
336 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
337 * it only displayed the last change. I'd disallow them, but they are
338 * useful in combination with the [v]global commands. In the current
339 * model the problem is combining them with the 'c' flag -- the screen
340 * would have to flip back and forth between the confirm screen and the
341 * ex print screen, which would be pretty awful. We do display all
342 * changes, though, for what that's worth.
345 * Historic vi was fairly strict about the order of "options", the
346 * count, and "flags". I'm somewhat fuzzy on the difference between
347 * options and flags, anyway, so this is a simpler approach, and we
348 * just take it them in whatever order the user gives them. (The ex
349 * usage statement doesn't reflect this.)
351 cflag
= gflag
= lflag
= nflag
= pflag
= rflag
= 0;
352 for (lno
= OOBLNO
; *s
!= '\0'; ++s
)
357 case '0': case '1': case '2': case '3': case '4':
358 case '5': case '6': case '7': case '8': case '9':
362 lno
= strtoul(s
, &s
, 10);
363 if (errno
== ERANGE
) {
365 msgq(sp
, M_ERR
, "Count overflow.");
366 else if (lno
== LONG_MIN
)
367 msgq(sp
, M_ERR
, "Count underflow.");
369 msgq(sp
, M_SYSERR
, NULL
);
373 * In historic vi, the count was inclusive from the
376 cmdp
->addr1
.lno
= cmdp
->addr2
.lno
;
377 cmdp
->addr2
.lno
+= lno
- 1;
395 if (LF_ISSET(SUB_FIRST
)) {
397 "Regular expression specified; r flag meaningless.");
400 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
402 "No previous regular expression.");
411 if (*s
!= '\0' || !rflag
&& LF_ISSET(SUB_MUSTSETR
)) {
412 usage
: msgq(sp
, M_ERR
, "Usage: %s", cmdp
->cmd
->usage
);
416 if (IN_VI_MODE(sp
) && cflag
&& (lflag
|| nflag
|| pflag
)) {
418 "The #, l and p flags may not be combined with the c flag in vi mode.");
422 /* Get some space. */
423 GET_SPACE_RET(sp
, bp
, blen
, 512);
426 * lb: build buffer pointer.
427 * lbclen: current length of built buffer.
428 * lblen; length of build buffer.
434 * Since multiple changes can happen in a line, we only increment
435 * the change count on the first change to a line.
439 /* For each line... */
440 for (quit
= 0, lno
= cmdp
->addr1
.lno
,
441 elno
= cmdp
->addr2
.lno
; !quit
&& lno
<= elno
; ++lno
) {
444 if ((s
= file_gline(sp
, ep
, lno
, &len
)) == NULL
) {
445 GETLINE_ERR(sp
, lno
);
450 * Make a local copy if doing confirmation -- when calling
451 * the confirm routine we're likely to lose our cached copy.
454 ADD_SPACE_RET(sp
, bp
, blen
, len
)
459 /* Reset the buffer pointer. */
462 /* Reset empty match flag. */
466 * We don't want to have to do a setline if the line didn't
467 * change -- keep track of whether or not this line changed.
471 /* New line, do EOL match. */
474 /* It's not nul terminated, but we pretend it is. */
475 eflags
= REG_STARTEND
;
477 /* The search area is from 's' to the end of the line. */
478 nextmatch
: sp
->match
[0].rm_so
= 0;
479 sp
->match
[0].rm_eo
= len
;
481 /* Get the next match. */
482 skipmatch
: eval
= regexec(re
,
483 (char *)s
, re
->re_nsub
+ 1, sp
->match
, eflags
);
486 * There wasn't a match -- if there was an error, deal with
487 * it. If there was a previous match in this line, resolve
488 * the changes into the database. Otherwise, just move on.
490 if (eval
== REG_NOMATCH
) {
496 re_error(sp
, eval
, re
);
502 * It's possible to match 0-length strings -- for example, the
503 * command s;a*;X;, when matched against the string "aabb" will
504 * result in "XbXbX", i.e. the matches are "aa", the space
505 * between the b's and the space between the b's and the end of
506 * the string. There is a similar space between the beginning
507 * of the string and the a's. The rule that we use (because vi
508 * historically used it) is that any 0-length match, occurring
509 * immediately after a match, is ignored. Otherwise, the above
510 * example would have resulted in "XXbXbX". Another example is
511 * incorrectly using " *" to replace groups of spaces with one
514 * The way we do this is that if we just had a successful match,
515 * the starting offset does not skip characters, and the match
516 * is empty, ignore the match and move forward. If there's no
517 * more characters in the string, we were attempting to match
518 * after the last character, so quit.
520 if (!empty_ok
&& sp
->match
[0].rm_so
== sp
->match
[0].rm_eo
) {
524 * Can't get here if !gflag or !linechanged, so just
525 * test cflag. Same logic also guarantees that offset
526 * has been initialized.
529 if (sp
->match
[0].rm_so
== offset
) {
535 sp
->match
[0].rm_eo
= len
;
539 if (sp
->match
[0].rm_so
== 0) {
549 /* Confirm change. */
552 * Set the cursor position for confirmation. Note,
553 * if we matched on a '$', the cursor may be past
557 * May want to "fix" this in the confirm routine;
558 * the confirm routine may be able to display a
562 from
.cno
= sp
->match
[0].rm_so
;
564 to
.cno
= sp
->match
[0].rm_eo
;
572 switch (sp
->s_confirm(sp
, ep
, &from
, &to
)) {
577 * Copy the bytes before the match and the
578 * bytes in the match into the build buffer.
580 BUILD(sp
, s
, sp
->match
[0].rm_eo
);
583 /* Set the quit flag. */
586 /* If interruptible, pass the info back. */
587 if (F_ISSET(sp
, S_INTERRUPTIBLE
))
588 F_SET(sp
, S_INTERRUPTED
);
591 * If any changes, resolve them, otherwise
592 * return to the main loop.
600 /* Copy the bytes before the match into the build buffer. */
601 BUILD(sp
, s
, sp
->match
[0].rm_so
);
604 * Update the cursor to the start of the change.
607 * Historic vi just put the cursor on the first non-blank
608 * of the last line changed. This might be better.
611 sp
->cno
= sp
->match
[0].rm_so
;
613 /* Substitute the matching bytes. */
614 if (regsub(sp
, s
, &lb
, &lbclen
, &lblen
))
617 /* Set the change flag so we know this line was modified. */
620 /* Move the pointers past the matched bytes. */
621 skip
: s
+= sp
->match
[0].rm_eo
;
622 len
-= sp
->match
[0].rm_eo
;
624 /* Got a match, turn off empty patterns. */
627 /* Only the first search matches anchored expression. */
628 eflags
|= REG_NOTBOL
;
631 * If doing a global change with confirmation, we have to
632 * update the screen. The basic idea is to store the line
633 * so the screen update routines can find it, but start at
636 if (linechanged
&& cflag
&& gflag
) {
640 /* Copy the suffix. */
644 /* Store inserted lines, adjusting the build buffer. */
647 for (cnt
= 0; cnt
< sp
->newl_cnt
;
648 ++cnt
, ++lno
, ++elno
, ++lastline
) {
649 if (file_iline(sp
, ep
, lno
,
650 lb
+ last
, sp
->newl
[cnt
] - last
))
652 last
= sp
->newl
[cnt
] + 1;
653 ++sp
->rptlines
[L_ADDED
];
661 /* Store and retrieve the line. */
662 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
664 if ((s
= file_gline(sp
, ep
, lno
, &len
)) == NULL
) {
665 GETLINE_ERR(sp
, lno
);
668 ADD_SPACE_RET(sp
, bp
, blen
, len
)
672 /* Restart the build. */
675 /* Update changed line counter. */
676 if (lastline
!= lno
) {
677 ++sp
->rptlines
[L_CHANGED
];
682 * Do a test for the after the string match. Set
683 * REG_NOTEOL so the '$' pattern only matches once.
690 eflags
|= REG_NOTEOL
;
693 /* Start in the middle of the line. */
694 sp
->match
[0].rm_so
= offset
;
695 sp
->match
[0].rm_eo
= len
;
702 * Do a test for the after the string match. Set
703 * REG_NOTEOL so the '$' pattern only matches once.
705 if (gflag
&& do_eol_match
) {
708 eflags
|= REG_NOTEOL
;
714 /* Copy any remaining bytes into the build buffer. */
718 /* Store inserted lines, adjusting the build buffer. */
721 for (cnt
= 0; cnt
< sp
->newl_cnt
;
722 ++cnt
, ++lno
, ++elno
, ++lastline
) {
723 if (file_iline(sp
, ep
,
724 lno
, lb
+ last
, sp
->newl
[cnt
] - last
))
726 last
= sp
->newl
[cnt
] + 1;
727 ++sp
->rptlines
[L_ADDED
];
735 /* Store the changed line. */
737 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
740 /* Update changed line counter. */
741 if (lastline
!= lno
) {
742 ++sp
->rptlines
[L_CHANGED
];
746 /* Display as necessary. */
747 if (lflag
|| nflag
|| pflag
) {
748 from
.lno
= to
.lno
= lno
;
749 from
.cno
= to
.cno
= 0;
751 ex_print(sp
, ep
, &from
, &to
, E_F_LIST
);
753 ex_print(sp
, ep
, &from
, &to
, E_F_HASH
);
755 ex_print(sp
, ep
, &from
, &to
, E_F_PRINT
);
760 * Cursor moves to last line changed, unless doing confirm,
761 * in which case don't move it.
763 if (!cflag
&& lastline
!= OOBLNO
)
767 * Note if nothing found. Else, if nothing displayed to the
768 * screen, put something up.
770 if (sp
->rptlines
[L_CHANGED
] == 0 && !F_ISSET(sp
, S_GLOBAL
))
771 msgq(sp
, M_INFO
, "No match found.");
772 else if (!lflag
&& !nflag
&& !pflag
)
773 F_SET(sp
, S_AUTOPRINT
);
775 FREE_SPACE(sp
, bp
, blen
);
778 ret1
: FREE_SPACE(sp
, bp
, blen
);
784 * Do the substitution for a regular expression.
787 regsub(sp
, ip
, lbp
, lbclenp
, lblenp
)
789 char *ip
; /* Input line. */
791 size_t *lbclenp
, *lblenp
;
793 enum { C_NOTSET
, C_LOWER
, C_ONELOWER
, C_ONEUPPER
, C_UPPER
} conv
;
794 size_t lbclen
, lblen
; /* Local copies. */
795 size_t mlen
; /* Match length. */
796 size_t rpl
; /* Remaining replacement length. */
797 char *rp
; /* Replacement pointer. */
799 int no
; /* Match replacement offset. */
800 char *p
, *t
; /* Buffer pointers. */
801 char *lb
; /* Local copies. */
803 lb
= *lbp
; /* Get local copies. */
810 * There are some special sequences that vi provides in the
811 * replacement patterns.
812 * & string the RE matched (\& if nomagic set)
813 * \# n-th regular subexpression
814 * \E end \U, \L conversion
815 * \e end \U, \L conversion
816 * \l convert the next character to lower-case
817 * \L convert to lower-case, until \E, \e, or end of replacement
818 * \u convert the next character to upper-case
819 * \U convert to upper-case, until \E, \e, or end of replacement
821 * Otherwise, since this is the lowest level of replacement, discard
822 * all escape characters. This (hopefully) follows historic practice.
824 #define ADDCH(ch) { \
826 __value = term_key_val(sp, ch); \
827 if (__value == K_CR || __value == K_NL) { \
829 sp->newl[sp->newl_cnt++] = lbclen; \
830 } else if (conv != C_NOTSET) { \
855 for (rp
= sp
->repl
, rpl
= sp
->repl_len
, p
= lb
+ lbclen
; rpl
--;) {
856 switch (ch
= *rp
++) {
858 if (O_ISSET(sp
, O_MAGIC
)) {
869 if (!O_ISSET(sp
, O_MAGIC
)) {
875 case '0': case '1': case '2': case '3': case '4':
876 case '5': case '6': case '7': case '8': case '9':
878 subzero
: if (sp
->match
[no
].rm_so
== -1 ||
879 sp
->match
[no
].rm_eo
== -1)
882 sp
->match
[no
].rm_eo
- sp
->match
[no
].rm_so
;
883 for (t
= ip
+ sp
->match
[no
].rm_so
; mlen
--; ++t
)
915 *lbp
= lb
; /* Update caller's information. */
922 checkmatchsize(sp
, re
)
926 /* Build nsub array as necessary. */
927 if (sp
->matchsize
< re
->re_nsub
+ 1) {
928 sp
->matchsize
= re
->re_nsub
+ 1;
929 REALLOC(sp
, sp
->match
,
930 regmatch_t
*, sp
->matchsize
* sizeof(regmatch_t
));
931 if (sp
->match
== NULL
) {