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.25 1993/12/17 16:22:38 bostic Exp $ (Berkeley) $Date: 1993/12/17 16:22:38 $";
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 * if O_MAGIC is set and it escapes a tilde.
173 if (sp
->repl
!= NULL
)
174 FREE(sp
->repl
, sp
->repl_len
);
179 * Count ~'s to figure out how much space we need. We could
180 * special case nonexistent last patterns or whether or not
181 * O_MAGIC is set, but it's probably not worth the effort.
183 for (rep
= p
, len
= 0;
184 p
[0] != '\0' && p
[0] != delim
; ++p
, ++len
)
187 GET_SPACE_RET(sp
, bp
, blen
, len
);
188 for (t
= bp
, len
= 0, p
= rep
;;) {
189 if (p
[0] == '\0' || p
[0] == delim
) {
197 else if (p
[1] == '~') {
199 if (!O_ISSET(sp
, O_MAGIC
))
202 } else if (p
[0] == '~' && O_ISSET(sp
, O_MAGIC
)) {
204 memmove(t
, sp
->repl
, sp
->repl_len
);
212 if (sp
->repl
!= NULL
)
213 FREE(sp
->repl
, sp
->repl_len
);
214 if ((sp
->repl
= malloc(len
)) == NULL
) {
215 msgq(sp
, M_SYSERR
, NULL
);
216 FREE_SPACE(sp
, bp
, blen
);
219 memmove(sp
->repl
, bp
, len
);
221 FREE_SPACE(sp
, bp
, blen
);
224 if (checkmatchsize(sp
, &sp
->subre
))
226 return (substitute(sp
, ep
, cmdp
, p
, re
, flags
));
231 * [line [,line]] & [cgr] [count] [#lp]]
233 * Substitute using the last substitute RE and replacement pattern.
236 ex_subagain(sp
, ep
, cmdp
)
241 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
242 msgq(sp
, M_ERR
, "No previous regular expression.");
245 return (substitute(sp
, ep
, cmdp
, cmdp
->argv
[0]->bp
, &sp
->subre
, 0));
250 * [line [,line]] ~ [cgr] [count] [#lp]]
252 * Substitute using the last RE and last substitute replacement pattern.
255 ex_subtilde(sp
, ep
, cmdp
)
260 if (!F_ISSET(sp
, S_SRE_SET
)) {
261 msgq(sp
, M_ERR
, "No previous regular expression.");
264 return (substitute(sp
, ep
, cmdp
, cmdp
->argv
[0]->bp
, &sp
->sre
, 0));
268 * The nasty part of the substitution is what happens when the replacement
269 * string contains newlines. It's a bit tricky -- consider the information
270 * that has to be retained for "s/f\(o\)o/^M\1^M\1/". The solution here is
271 * to build a set of newline offets which we use to break the line up later,
272 * when the replacement is done. Don't change it unless you're pretty damned
275 #define NEEDNEWLINE(sp) { \
276 if (sp->newl_len == sp->newl_cnt) { \
277 sp->newl_len += 25; \
278 REALLOC(sp, sp->newl, size_t *, \
279 sp->newl_len * sizeof(size_t)); \
280 if (sp->newl == NULL) { \
287 #define BUILD(sp, l, len) { \
288 if (lbclen + (len) > lblen) { \
289 lblen += MAX(lbclen + (len), 256); \
290 REALLOC(sp, lb, char *, lblen); \
296 memmove(lb + lbclen, l, len); \
300 #define NEEDSP(sp, len, pnt) { \
301 if (lbclen + (len) > lblen) { \
302 lblen += MAX(lbclen + (len), 256); \
303 REALLOC(sp, lb, char *, lblen); \
314 * Do the substitution. This stuff is *really* tricky. There are
315 * lots of special cases, and general nastiness. Don't mess with it
316 * unless you're pretty confident.
319 substitute(sp
, ep
, cmdp
, s
, re
, flags
)
328 recno_t elno
, lno
, lastline
;
329 size_t blen
, cnt
, last
, lbclen
, lblen
, len
, offset
;
330 int do_eol_match
, eflags
, empty_ok
, eval
, linechanged
, quit
;
331 int cflag
, gflag
, lflag
, nflag
, pflag
, rflag
;
335 * Historic vi permitted the '#', 'l' and 'p' options in vi mode, but
336 * it only displayed the last change. I'd disallow them, but they are
337 * useful in combination with the [v]global commands. In the current
338 * model the problem is combining them with the 'c' flag -- the screen
339 * would have to flip back and forth between the confirm screen and the
340 * ex print screen, which would be pretty awful. We do display all
341 * changes, though, for what that's worth.
344 * Historic vi was fairly strict about the order of "options", the
345 * count, and "flags". I'm somewhat fuzzy on the difference between
346 * options and flags, anyway, so this is a simpler approach, and we
347 * just take it them in whatever order the user gives them. (The ex
348 * usage statement doesn't reflect this.)
350 cflag
= gflag
= lflag
= nflag
= pflag
= rflag
= 0;
351 for (lno
= OOBLNO
; *s
!= '\0'; ++s
)
356 case '0': case '1': case '2': case '3': case '4':
357 case '5': case '6': case '7': case '8': case '9':
361 lno
= strtoul(s
, &s
, 10);
362 if (errno
== ERANGE
) {
364 msgq(sp
, M_ERR
, "Count overflow.");
365 else if (lno
== LONG_MIN
)
366 msgq(sp
, M_ERR
, "Count underflow.");
368 msgq(sp
, M_SYSERR
, NULL
);
372 * In historic vi, the count was inclusive from the
375 cmdp
->addr1
.lno
= cmdp
->addr2
.lno
;
376 cmdp
->addr2
.lno
+= lno
- 1;
394 if (LF_ISSET(SUB_FIRST
)) {
396 "Regular expression specified; r flag meaningless.");
399 if (!F_ISSET(sp
, S_SUBRE_SET
)) {
401 "No previous regular expression.");
410 if (*s
!= '\0' || !rflag
&& LF_ISSET(SUB_MUSTSETR
)) {
411 usage
: msgq(sp
, M_ERR
, "Usage: %s", cmdp
->cmd
->usage
);
415 if (IN_VI_MODE(sp
) && cflag
&& (lflag
|| nflag
|| pflag
)) {
417 "The #, l and p flags may not be combined with the c flag in vi mode.");
421 /* Get some space. */
422 GET_SPACE_RET(sp
, bp
, blen
, 512);
425 * lb: build buffer pointer.
426 * lbclen: current length of built buffer.
427 * lblen; length of build buffer.
433 * Since multiple changes can happen in a line, we only increment
434 * the change count on the first change to a line.
438 /* For each line... */
439 for (quit
= 0, lno
= cmdp
->addr1
.lno
,
440 elno
= cmdp
->addr2
.lno
; !quit
&& lno
<= elno
; ++lno
) {
443 if ((s
= file_gline(sp
, ep
, lno
, &len
)) == NULL
) {
444 GETLINE_ERR(sp
, lno
);
449 * Make a local copy if doing confirmation -- when calling
450 * the confirm routine we're likely to lose our cached copy.
453 ADD_SPACE_RET(sp
, bp
, blen
, len
)
458 /* Reset the buffer pointer. */
461 /* Reset empty match flag. */
465 * We don't want to have to do a setline if the line didn't
466 * change -- keep track of whether or not this line changed.
470 /* New line, do EOL match. */
473 /* It's not nul terminated, but we pretend it is. */
474 eflags
= REG_STARTEND
;
476 /* The search area is from 's' to the end of the line. */
477 nextmatch
: sp
->match
[0].rm_so
= 0;
478 sp
->match
[0].rm_eo
= len
;
480 /* Get the next match. */
481 skipmatch
: eval
= regexec(re
,
482 (char *)s
, re
->re_nsub
+ 1, sp
->match
, eflags
);
485 * There wasn't a match -- if there was an error, deal with
486 * it. If there was a previous match in this line, resolve
487 * the changes into the database. Otherwise, just move on.
489 if (eval
== REG_NOMATCH
) {
495 re_error(sp
, eval
, re
);
501 * It's possible to match 0-length strings -- for example, the
502 * command s;a*;X;, when matched against the string "aabb" will
503 * result in "XbXbX", i.e. the matches are "aa", the space
504 * between the b's and the space between the b's and the end of
505 * the string. There is a similar space between the beginning
506 * of the string and the a's. The rule that we use (because vi
507 * historically used it) is that any 0-length match, occurring
508 * immediately after a match, is ignored. Otherwise, the above
509 * example would have resulted in "XXbXbX". Another example is
510 * incorrectly using " *" to replace groups of spaces with one
513 * The way we do this is that if we just had a successful match,
514 * the starting offset does not skip characters, and the match
515 * is empty, ignore the match and move forward. If there's no
516 * more characters in the string, we were attempting to match
517 * after the last character, so quit.
519 if (!empty_ok
&& sp
->match
[0].rm_so
== sp
->match
[0].rm_eo
) {
523 * Can't get here if !gflag or !linechanged, so just
524 * test cflag. Same logic also guarantees that offset
525 * has been initialized.
528 if (sp
->match
[0].rm_so
== offset
) {
534 sp
->match
[0].rm_eo
= len
;
538 if (sp
->match
[0].rm_so
== 0) {
548 /* Confirm change. */
551 * Set the cursor position for confirmation. Note,
552 * if we matched on a '$', the cursor may be past
556 * May want to "fix" this in the confirm routine;
557 * the confirm routine may be able to display a
561 from
.cno
= sp
->match
[0].rm_so
;
563 to
.cno
= sp
->match
[0].rm_eo
;
571 switch (sp
->s_confirm(sp
, ep
, &from
, &to
)) {
576 * Copy the bytes before the match and the
577 * bytes in the match into the build buffer.
579 BUILD(sp
, s
, sp
->match
[0].rm_eo
);
582 /* Set the quit flag. */
585 /* If interruptible, pass the info back. */
586 if (F_ISSET(sp
, S_INTERRUPTIBLE
))
587 F_SET(sp
, S_INTERRUPTED
);
590 * If any changes, resolve them, otherwise
591 * return to the main loop.
599 /* Copy the bytes before the match into the build buffer. */
600 BUILD(sp
, s
, sp
->match
[0].rm_so
);
603 * Update the cursor to the start of the change.
606 * Historic vi just put the cursor on the first non-blank
607 * of the last line changed. This might be better.
610 sp
->cno
= sp
->match
[0].rm_so
;
612 /* Substitute the matching bytes. */
613 if (regsub(sp
, s
, &lb
, &lbclen
, &lblen
))
616 /* Set the change flag so we know this line was modified. */
619 /* Move the pointers past the matched bytes. */
620 skip
: s
+= sp
->match
[0].rm_eo
;
621 len
-= sp
->match
[0].rm_eo
;
623 /* Got a match, turn off empty patterns. */
626 /* Only the first search matches anchored expression. */
627 eflags
|= REG_NOTBOL
;
630 * If doing a global change with confirmation, we have to
631 * update the screen. The basic idea is to store the line
632 * so the screen update routines can find it, but start at
635 if (linechanged
&& cflag
&& gflag
) {
639 /* Copy the suffix. */
643 /* Store inserted lines, adjusting the build buffer. */
646 for (cnt
= 0; cnt
< sp
->newl_cnt
;
647 ++cnt
, ++lno
, ++elno
, ++lastline
) {
648 if (file_iline(sp
, ep
, lno
,
649 lb
+ last
, sp
->newl
[cnt
] - last
))
651 last
= sp
->newl
[cnt
] + 1;
652 ++sp
->rptlines
[L_ADDED
];
660 /* Store and retrieve the line. */
661 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
663 if ((s
= file_gline(sp
, ep
, lno
, &len
)) == NULL
) {
664 GETLINE_ERR(sp
, lno
);
667 ADD_SPACE_RET(sp
, bp
, blen
, len
)
671 /* Restart the build. */
674 /* Update changed line counter. */
675 if (lastline
!= lno
) {
676 ++sp
->rptlines
[L_CHANGED
];
681 * Do a test for the after the string match. Set
682 * REG_NOTEOL so the '$' pattern only matches once.
689 eflags
|= REG_NOTEOL
;
692 /* Start in the middle of the line. */
693 sp
->match
[0].rm_so
= offset
;
694 sp
->match
[0].rm_eo
= len
;
701 * Do a test for the after the string match. Set
702 * REG_NOTEOL so the '$' pattern only matches once.
704 if (gflag
&& do_eol_match
) {
707 eflags
|= REG_NOTEOL
;
713 /* Copy any remaining bytes into the build buffer. */
717 /* Store inserted lines, adjusting the build buffer. */
720 for (cnt
= 0; cnt
< sp
->newl_cnt
;
721 ++cnt
, ++lno
, ++elno
, ++lastline
) {
722 if (file_iline(sp
, ep
,
723 lno
, lb
+ last
, sp
->newl
[cnt
] - last
))
725 last
= sp
->newl
[cnt
] + 1;
726 ++sp
->rptlines
[L_ADDED
];
734 /* Store the changed line. */
736 if (file_sline(sp
, ep
, lno
, lb
+ last
, lbclen
))
739 /* Update changed line counter. */
740 if (lastline
!= lno
) {
741 ++sp
->rptlines
[L_CHANGED
];
745 /* Display as necessary. */
746 if (lflag
|| nflag
|| pflag
) {
747 from
.lno
= to
.lno
= lno
;
748 from
.cno
= to
.cno
= 0;
750 ex_print(sp
, ep
, &from
, &to
, E_F_LIST
);
752 ex_print(sp
, ep
, &from
, &to
, E_F_HASH
);
754 ex_print(sp
, ep
, &from
, &to
, E_F_PRINT
);
759 * Cursor moves to last line changed, unless doing confirm,
760 * in which case don't move it.
762 if (!cflag
&& lastline
!= OOBLNO
)
766 * Note if nothing found. Else, if nothing displayed to the
767 * screen, put something up.
769 if (sp
->rptlines
[L_CHANGED
] == 0 && !F_ISSET(sp
, S_GLOBAL
))
770 msgq(sp
, M_INFO
, "No match found.");
771 else if (!lflag
&& !nflag
&& !pflag
)
772 F_SET(sp
, S_AUTOPRINT
);
774 FREE_SPACE(sp
, bp
, blen
);
777 ret1
: FREE_SPACE(sp
, bp
, blen
);
783 * Do the substitution for a regular expression.
786 regsub(sp
, ip
, lbp
, lbclenp
, lblenp
)
788 char *ip
; /* Input line. */
790 size_t *lbclenp
, *lblenp
;
792 enum { C_NOTSET
, C_LOWER
, C_ONELOWER
, C_ONEUPPER
, C_UPPER
} conv
;
793 size_t lbclen
, lblen
; /* Local copies. */
794 size_t mlen
; /* Match length. */
795 size_t rpl
; /* Remaining replacement length. */
796 char *rp
; /* Replacement pointer. */
798 int no
; /* Match replacement offset. */
799 char *p
, *t
; /* Buffer pointers. */
800 char *lb
; /* Local copies. */
802 lb
= *lbp
; /* Get local copies. */
809 * There are some special sequences that vi provides in the
810 * replacement patterns.
811 * & string the RE matched (\& if nomagic set)
812 * \# n-th regular subexpression
813 * \E end \U, \L conversion
814 * \e end \U, \L conversion
815 * \l convert the next character to lower-case
816 * \L convert to lower-case, until \E, \e, or end of replacement
817 * \u convert the next character to upper-case
818 * \U convert to upper-case, until \E, \e, or end of replacement
820 * Otherwise, since this is the lowest level of replacement, discard
821 * all escape characters. This (hopefully) follows historic practice.
823 #define ADDCH(ch) { \
825 __value = term_key_val(sp, ch); \
826 if (__value == K_CR || __value == K_NL) { \
828 sp->newl[sp->newl_cnt++] = lbclen; \
829 } else if (conv != C_NOTSET) { \
854 for (rp
= sp
->repl
, rpl
= sp
->repl_len
, p
= lb
+ lbclen
; rpl
--;) {
855 switch (ch
= *rp
++) {
857 if (O_ISSET(sp
, O_MAGIC
)) {
868 if (!O_ISSET(sp
, O_MAGIC
)) {
874 case '0': case '1': case '2': case '3': case '4':
875 case '5': case '6': case '7': case '8': case '9':
877 subzero
: if (sp
->match
[no
].rm_so
== -1 ||
878 sp
->match
[no
].rm_eo
== -1)
881 sp
->match
[no
].rm_eo
- sp
->match
[no
].rm_so
;
882 for (t
= ip
+ sp
->match
[no
].rm_so
; mlen
--; ++t
)
914 *lbp
= lb
; /* Update caller's information. */
921 checkmatchsize(sp
, re
)
925 /* Build nsub array as necessary. */
926 if (sp
->matchsize
< re
->re_nsub
+ 1) {
927 sp
->matchsize
= re
->re_nsub
+ 1;
928 REALLOC(sp
, sp
->match
,
929 regmatch_t
*, sp
->matchsize
* sizeof(regmatch_t
));
930 if (sp
->match
== NULL
) {