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.
13 static const char sccsid
[] = "$Id: ex_subst.c,v 10.39 1996/12/16 09:40:10 bostic Exp $ (Berkeley) $Date: 1996/12/16 09:40:10 $";
16 #include <sys/types.h>
17 #include <sys/queue.h>
20 #include <bitstring.h>
29 #include "../common/common.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
));
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 *));
59 char *bp
, *ptrn
, *rep
, *p
, *t
;
62 * Skip leading white space.
65 * Historic vi allowed any non-alphanumeric to serve as the
66 * substitution command delimiter.
69 * If the arguments are empty, it's the same as &, i.e. we
70 * repeat the last substitution.
74 for (p
= cmdp
->argv
[0]->bp
,
75 len
= cmdp
->argv
[0]->len
; len
> 0; --len
, ++p
) {
80 subagain
: return (ex_subagain(sp
, cmdp
));
83 if (isalnum(delim
) || delim
== '\\')
84 return (s(sp
, cmdp
, p
, &sp
->subre_c
, SUB_MUSTSETR
));
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.
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"
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
) {
118 * Nul terminate the pattern string -- it's passed
119 * to regcomp which doesn't understand anything else.
127 else if (p
[1] == '\\')
133 * If the pattern string is empty, use the last RE (not just the
134 * last substitution RE).
137 if (sp
->re
== NULL
) {
138 ex_emsg(sp
, NULL
, EXM_NOPREVRE
);
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
))
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
))
159 if (re_compile(sp
, ptrn
, t
- ptrn
, &sp
->subre
,
160 &sp
->subre_len
, &sp
->subre_c
, SEARCH_CSUBST
| SEARCH_MSG
))
164 sp
->searchdir
= FORWARD
;
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
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.
183 * Only toss an escaping character if it escapes a delimiter or
184 * if O_MAGIC is set and it escapes a tilde.
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
) {
195 if (sp
->repl
!= NULL
)
199 } else if (p
[0] == '%' && (p
[1] == '\0' || p
[1] == delim
))
200 p
+= p
[1] == delim
? 2 : 1;
202 for (rep
= p
, len
= 0;
203 p
[0] != '\0' && p
[0] != delim
; ++p
, ++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
) {
216 else if (p
[1] == '\\') {
219 } else if (p
[1] == '~') {
221 if (!O_ISSET(sp
, O_MAGIC
))
224 } else if (p
[0] == '~' && O_ISSET(sp
, O_MAGIC
)) {
226 memcpy(t
, sp
->repl
, sp
->repl_len
);
234 if ((sp
->repl_len
= len
) != 0) {
235 if (sp
->repl
!= NULL
)
237 if ((sp
->repl
= malloc(len
)) == NULL
) {
238 msgq(sp
, M_SYSERR
, NULL
);
239 FREE_SPACE(sp
, bp
, blen
);
242 memcpy(sp
->repl
, bp
, len
);
244 FREE_SPACE(sp
, bp
, blen
);
246 return (s(sp
, cmdp
, p
, re
, flags
));
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
)
262 if (sp
->subre
== NULL
) {
263 ex_emsg(sp
, NULL
, EXM_NOPREVRE
);
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
))
271 cmdp
, cmdp
->argc
? cmdp
->argv
[0]->bp
: NULL
, &sp
->subre_c
, 0));
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
)
287 if (sp
->re
== NULL
) {
288 ex_emsg(sp
, NULL
, EXM_NOPREVRE
);
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
))
295 cmdp
, cmdp
->argc
? cmdp
->argv
[0]->bp
: NULL
, &sp
->re_c
, 0));
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
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*
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) { \
323 #define BUILD(sp, l, len) { \
324 if (lbclen + (len) > lblen) { \
325 lblen += MAX(lbclen + (len), 256); \
326 REALLOC(sp, lb, char *, lblen); \
332 memcpy(lb + lbclen, l, len); \
336 #define NEEDSP(sp, len, pnt) { \
337 if (lbclen + (len) > lblen) { \
338 lblen += MAX(lbclen + (len), 256); \
339 REALLOC(sp, lb, char *, lblen); \
349 s(sp
, cmdp
, s
, re
, flags
)
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
;
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.
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;
403 for (lno
= OOBLNO
; *s
!= '\0'; ++s
)
414 case '0': case '1': case '2': case '3': case '4':
415 case '5': case '6': case '7': case '8': case '9':
419 lno
= strtoul(s
, &s
, 10);
420 if (*s
== '\0') /* Loop increment correction. */
422 if (errno
== ERANGE
) {
424 msgq(sp
, M_ERR
, "153|Count overflow");
425 else if (lno
== LONG_MIN
)
426 msgq(sp
, M_ERR
, "154|Count underflow");
428 msgq(sp
, M_SYSERR
, NULL
);
432 * In historic vi, the count was inclusive from the
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
))
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
));
454 sp
->g_suffix
= !sp
->g_suffix
;
463 if (LF_ISSET(SUB_FIRST
)) {
465 "155|Regular expression specified; r flag meaningless");
468 if (!F_ISSET(sp
, SC_RE_SEARCH
)) {
469 ex_emsg(sp
, NULL
, EXM_NOPREVRE
);
479 if (*s
!= '\0' || !rflag
&& LF_ISSET(SUB_MUSTSETR
)) {
480 usage
: ex_emsg(sp
, cmdp
->cmd
->usage
, EXM_USAGE
);
484 noargs
: if (F_ISSET(sp
, SC_VI
) && sp
->c_suffix
&& (lflag
|| nflag
|| pflag
)) {
486 "156|The #, l and p flags may not be combined with the c flag in vi mode");
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.
498 blen
= lbclen
= lblen
= 0;
500 /* For each line... */
501 for (matched
= quit
= 0, lno
= cmdp
->addr1
.lno
,
502 elno
= cmdp
->addr2
.lno
; !quit
&& lno
<= elno
; ++lno
) {
504 /* Someone's unhappy, time to stop. */
509 if (db_get(sp
, lno
, DBG_FATAL
, &s
, &llen
))
513 * Make a local copy if doing confirmation -- when calling
514 * the confirm routine we're likely to lose the cached copy.
518 GET_SPACE_RET(sp
, bp
, blen
, llen
);
520 ADD_SPACE_RET(sp
, bp
, blen
, llen
);
525 /* Start searching from the beginning. */
529 /* Reset the build buffer offset. */
532 /* Reset empty match flag. */
536 * We don't want to have to do a setline if the line didn't
537 * change -- keep track of whether or not this line changed.
538 * If doing confirmations, don't want to keep setting the
539 * line if change is refused -- keep track of substitutions.
541 didsub
= linechanged
= 0;
543 /* New line, do an EOL match. */
546 /* It's not nul terminated, but we pretend it is. */
547 eflags
= REG_STARTEND
;
550 * The search area is from s + offset to the EOL.
552 * Generally, match[0].rm_so is the offset of the start
553 * of the match from the start of the search, and offset
554 * is the offset of the start of the last search.
556 nextmatch
: match
[0].rm_so
= 0;
557 match
[0].rm_eo
= len
;
559 /* Get the next match. */
560 eval
= regexec(re
, (char *)s
+ offset
, 10, match
, eflags
);
563 * There wasn't a match or if there was an error, deal with
564 * it. If there was a previous match in this line, resolve
565 * the changes into the database. Otherwise, just move on.
567 if (eval
== REG_NOMATCH
)
570 re_error(sp
, eval
, re
);
575 /* Only the first search can match an anchored expression. */
576 eflags
|= REG_NOTBOL
;
580 * It's possible to match 0-length strings -- for example, the
581 * command s;a*;X;, when matched against the string "aabb" will
582 * result in "XbXbX", i.e. the matches are "aa", the space
583 * between the b's and the space between the b's and the end of
584 * the string. There is a similar space between the beginning
585 * of the string and the a's. The rule that we use (because vi
586 * historically used it) is that any 0-length match, occurring
587 * immediately after a match, is ignored. Otherwise, the above
588 * example would have resulted in "XXbXbX". Another example is
589 * incorrectly using " *" to replace groups of spaces with one
592 * The way we do this is that if we just had a successful match,
593 * the starting offset does not skip characters, and the match
594 * is empty, ignore the match and move forward. If there's no
595 * more characters in the string, we were attempting to match
596 * after the last character, so quit.
598 if (!empty_ok
&& match
[0].rm_so
== 0 && match
[0].rm_eo
== 0) {
602 BUILD(sp
, s
+ offset
, 1)
608 /* Confirm change. */
611 * Set the cursor position for confirmation. Note,
612 * if we matched on a '$', the cursor may be past
615 from
.lno
= to
.lno
= lno
;
616 from
.cno
= match
[0].rm_so
+ offset
;
617 to
.cno
= match
[0].rm_eo
+ offset
;
619 * Both ex and vi have to correct for a change before
620 * the first character in the line.
623 from
.cno
= to
.cno
= 0;
624 if (F_ISSET(sp
, SC_VI
)) {
626 * Only vi has to correct for a change after
627 * the last character in the line.
630 * It would be nice to change the vi code so
631 * that we could display a cursor past EOL.
635 if (from
.cno
>= llen
)
640 if (vs_refresh(sp
, 1))
643 vs_update(sp
, msg_cat(sp
,
644 "169|Confirm change? [n]", NULL
), NULL
);
646 if (v_event_get(sp
, &ev
, 0, 0))
648 switch (ev
.e_event
) {
656 v_event_err(sp
, &ev
);
660 if (ex_print(sp
, cmdp
, &from
, &to
, 0) ||
661 ex_scprint(sp
, &from
, &to
))
663 if (ex_txt(sp
, &tiq
, 0, TXT_CR
))
665 ev
.e_c
= tiq
.cqh_first
->lb
[0];
674 BUILD(sp
, s
+offset
, match
[0].rm_eo
);
677 /* Set the quit/interrupted flags. */
679 F_SET(sp
->gp
, G_INTERRUPTED
);
682 * Resolve any changes, then return to (and
683 * exit from) the main loop.
690 * Set the cursor to the last position changed, converting
691 * from 1-based to 0-based.
694 sp
->cno
= match
[0].rm_so
;
696 /* Copy the bytes before the match into the build buffer. */
697 BUILD(sp
, s
+ offset
, match
[0].rm_so
);
699 /* Substitute the matching bytes. */
701 if (re_sub(sp
, s
+ offset
, &lb
, &lbclen
, &lblen
, match
))
704 /* Set the change flag so we know this line was modified. */
707 /* Move past the matched bytes. */
708 skip
: offset
+= match
[0].rm_eo
;
709 len
-= match
[0].rm_eo
;
711 /* A match cannot be followed by an empty pattern. */
715 * If doing a global change with confirmation, we have to
716 * update the screen. The basic idea is to store the line
717 * so the screen update routines can find it, and restart.
719 if (didsub
&& sp
->c_suffix
&& sp
->g_suffix
) {
721 * The new search offset will be the end of the
724 saved_offset
= lbclen
;
726 /* Copy the rest of the line. */
728 BUILD(sp
, s
+ offset
, len
)
730 /* Set the new offset. */
731 offset
= saved_offset
;
733 /* Store inserted lines, adjusting the build buffer. */
737 cnt
< sp
->newl_cnt
; ++cnt
, ++lno
, ++elno
) {
738 if (db_insert(sp
, lno
,
739 lb
+ last
, sp
->newl
[cnt
] - last
))
741 last
= sp
->newl
[cnt
] + 1;
742 ++sp
->rptlines
[L_ADDED
];
749 /* Store and retrieve the line. */
750 if (db_set(sp
, lno
, lb
+ last
, lbclen
))
752 if (db_get(sp
, lno
, DBG_FATAL
, &s
, &llen
))
754 ADD_SPACE_RET(sp
, bp
, blen
, llen
)
759 /* Restart the build. */
761 BUILD(sp
, s
, offset
);
764 * If we haven't already done the after-the-string
765 * match, do one. Set REG_NOTEOL so the '$' pattern
772 eflags
|= REG_NOTEOL
;
780 * If at the end of the string, do a test for the after
781 * the string match. Set REG_NOTEOL so the '$' pattern
784 if (sp
->g_suffix
&& do_eol_match
) {
787 eflags
|= REG_NOTEOL
;
792 endmatch
: if (!linechanged
)
795 /* Copy any remaining bytes into the build buffer. */
797 BUILD(sp
, s
+ offset
, len
)
799 /* Store inserted lines, adjusting the build buffer. */
803 cnt
< sp
->newl_cnt
; ++cnt
, ++lno
, ++elno
) {
805 lno
, lb
+ last
, sp
->newl
[cnt
] - last
))
807 last
= sp
->newl
[cnt
] + 1;
808 ++sp
->rptlines
[L_ADDED
];
814 /* Store the changed line. */
815 if (db_set(sp
, lno
, lb
+ last
, lbclen
))
818 /* Update changed line counter. */
819 if (sp
->rptlchange
!= lno
) {
820 sp
->rptlchange
= lno
;
821 ++sp
->rptlines
[L_CHANGED
];
826 * Display as necessary. Historic practice is to only
827 * display the last line of a line split into multiple
830 if (lflag
|| nflag
|| pflag
) {
831 from
.lno
= to
.lno
= lno
;
832 from
.cno
= to
.cno
= 0;
834 (void)ex_print(sp
, cmdp
, &from
, &to
, E_C_LIST
);
836 (void)ex_print(sp
, cmdp
, &from
, &to
, E_C_HASH
);
838 (void)ex_print(sp
, cmdp
, &from
, &to
, E_C_PRINT
);
844 * Historically, vi attempted to leave the cursor at the same place if
845 * the substitution was done at the current cursor position. Otherwise
846 * it moved it to the first non-blank of the last line changed. There
847 * were some problems: for example, :s/$/foo/ with the cursor on the
848 * last character of the line left the cursor on the last character, or
849 * the & command with multiple occurrences of the matching string in the
850 * line usually left the cursor in a fairly random position.
852 * We try to do the same thing, with the exception that if the user is
853 * doing substitution with confirmation, we move to the last line about
854 * which the user was consulted, as opposed to the last line that they
855 * actually changed. This prevents a screen flash if the user doesn't
856 * change many of the possible lines.
858 if (!sp
->c_suffix
&& (sp
->lno
!= slno
|| sp
->cno
!= scno
)) {
860 (void)nonblank(sp
, sp
->lno
, &sp
->cno
);
864 * If not in a global command, and nothing matched, say so.
865 * Else, if none of the lines displayed, put something up.
869 if (!F_ISSET(sp
, SC_EX_GLOBAL
)) {
870 msgq(sp
, M_ERR
, "157|No match found");
873 } else if (!lflag
&& !nflag
&& !pflag
)
874 F_SET(cmdp
, E_AUTOPRINT
);
881 FREE_SPACE(sp
, bp
, blen
);
891 * PUBLIC: int re_compile __P((SCR *,
892 * PUBLIC: char *, size_t, char **, size_t *, regex_t *, u_int));
895 re_compile(sp
, ptrn
, plen
, ptrnp
, lenp
, rep
, flags
)
903 int reflags
, replaced
, rval
;
908 if (LF_ISSET(SEARCH_EXTEND
))
909 reflags
|= REG_EXTENDED
;
910 if (LF_ISSET(SEARCH_IC
))
911 reflags
|= REG_ICASE
;
912 if (LF_ISSET(SEARCH_LITERAL
))
913 reflags
|= REG_NOSPEC
;
914 if (!LF_ISSET(SEARCH_NOOPT
| SEARCH_CSCOPE
| SEARCH_TAG
)) {
915 if (O_ISSET(sp
, O_EXTENDED
))
916 reflags
|= REG_EXTENDED
;
917 if (O_ISSET(sp
, O_IGNORECASE
))
918 reflags
|= REG_ICASE
;
919 if (O_ISSET(sp
, O_ICLOWER
))
922 if (LF_ISSET(SEARCH_ICL
)) {
923 iclower
: for (p
= ptrn
, len
= plen
; len
> 0; ++p
, --len
)
927 reflags
|= REG_ICASE
;
930 /* If we're replacing a saved value, clear the old one. */
931 if (LF_ISSET(SEARCH_CSEARCH
) && F_ISSET(sp
, SC_RE_SEARCH
)) {
933 F_CLR(sp
, SC_RE_SEARCH
);
935 if (LF_ISSET(SEARCH_CSUBST
) && F_ISSET(sp
, SC_RE_SUBST
)) {
936 regfree(&sp
->subre_c
);
937 F_CLR(sp
, SC_RE_SUBST
);
941 * If we're saving the string, it's a pattern we haven't seen before,
942 * so convert the vi-style RE's to POSIX 1003.2 RE's. Save a copy for
943 * later recompilation. Free any previously saved value.
947 if (LF_ISSET(SEARCH_CSCOPE
)) {
948 if (re_cscope_conv(sp
, &ptrn
, &plen
, &replaced
))
952 * Currently, the match-any-<blank> expression used in
953 * re_cscope_conv() requires extended RE's. This may
954 * not be right or safe.
956 reflags
|= REG_EXTENDED
;
957 } else if (LF_ISSET(SEARCH_TAG
)) {
958 if (re_tag_conv(sp
, &ptrn
, &plen
, &replaced
))
960 } else if (!LF_ISSET(SEARCH_LITERAL
))
961 if (re_conv(sp
, &ptrn
, &plen
, &replaced
))
964 /* Discard previous pattern. */
965 if (*ptrnp
!= NULL
) {
973 * Copy the string into allocated memory.
976 * Regcomp isn't 8-bit clean, so the pattern is nul-terminated
977 * for now. There's just no other solution.
979 MALLOC(sp
, *ptrnp
, char *, plen
+ 1);
980 if (*ptrnp
!= NULL
) {
981 memcpy(*ptrnp
, ptrn
, plen
);
982 (*ptrnp
)[plen
] = '\0';
985 /* Free up conversion-routine-allocated memory. */
987 FREE_SPACE(sp
, ptrn
, 0);
997 * Regcomp isn't 8-bit clean, so we just lost if the pattern
998 * contained a nul. Bummer!
1000 if ((rval
= regcomp(rep
, ptrn
, /* plen, */ reflags
)) != 0) {
1001 if (LF_ISSET(SEARCH_MSG
))
1002 re_error(sp
, rval
, rep
);
1006 if (LF_ISSET(SEARCH_CSEARCH
))
1007 F_SET(sp
, SC_RE_SEARCH
);
1008 if (LF_ISSET(SEARCH_CSUBST
))
1009 F_SET(sp
, SC_RE_SUBST
);
1016 * Convert vi's regular expressions into something that the
1017 * the POSIX 1003.2 RE functions can handle.
1019 * There are three conversions we make to make vi's RE's (specifically
1020 * the global, search, and substitute patterns) work with POSIX RE's.
1022 * 1: If O_MAGIC is not set, strip backslashes from the magic character
1023 * set (.[*~) that have them, and add them to the ones that don't.
1024 * 2: If O_MAGIC is not set, the string "\~" is replaced with the text
1025 * from the last substitute command's replacement string. If O_MAGIC
1026 * is set, it's the string "~".
1027 * 3: The pattern \<ptrn\> does "word" searches, convert it to use the
1031 * This doesn't exactly match the historic behavior of vi because we do
1032 * the ~ substitution before calling the RE engine, so magic characters
1033 * in the replacement string will be expanded by the RE engine, and they
1034 * weren't historically. It's a bug.
1037 re_conv(sp
, ptrnp
, plenp
, replacedp
)
1043 size_t blen
, len
, needlen
;
1048 * First pass through, we figure out how much space we'll need.
1049 * We do it in two passes, on the grounds that most of the time
1050 * the user is doing a search and won't have magic characters.
1051 * That way we can skip most of the memory allocation and copies.
1054 for (p
= *ptrnp
, len
= *plenp
, needlen
= 0; len
> 0; ++p
, --len
)
1062 needlen
+= sizeof(RE_WSTART
);
1066 needlen
+= sizeof(RE_WSTOP
);
1069 if (!O_ISSET(sp
, O_MAGIC
)) {
1071 needlen
+= sp
->repl_len
;
1077 if (!O_ISSET(sp
, O_MAGIC
)) {
1089 if (O_ISSET(sp
, O_MAGIC
)) {
1091 needlen
+= sp
->repl_len
;
1097 if (!O_ISSET(sp
, O_MAGIC
)) {
1112 /* Get enough memory to hold the final pattern. */
1114 GET_SPACE_RET(sp
, bp
, blen
, needlen
);
1116 for (p
= *ptrnp
, len
= *plenp
, t
= bp
; len
> 0; ++p
, --len
)
1124 RE_WSTART
, sizeof(RE_WSTART
) - 1);
1125 t
+= sizeof(RE_WSTART
) - 1;
1129 RE_WSTOP
, sizeof(RE_WSTOP
) - 1);
1130 t
+= sizeof(RE_WSTOP
) - 1;
1133 if (O_ISSET(sp
, O_MAGIC
))
1137 sp
->repl
, sp
->repl_len
);
1144 if (O_ISSET(sp
, O_MAGIC
))
1156 if (O_ISSET(sp
, O_MAGIC
)) {
1157 memcpy(t
, sp
->repl
, sp
->repl_len
);
1165 if (!O_ISSET(sp
, O_MAGIC
))
1181 * Convert a tags search path into something that the POSIX
1182 * 1003.2 RE functions can handle.
1185 re_tag_conv(sp
, ptrnp
, plenp
, replacedp
)
1197 /* Max memory usage is 2 times the length of the string. */
1199 GET_SPACE_RET(sp
, bp
, blen
, len
* 2);
1204 /* If the last character is a '/' or '?', we just strip it. */
1205 if (len
> 0 && (p
[len
- 1] == '/' || p
[len
- 1] == '?'))
1208 /* If the next-to-last or last character is a '$', it's magic. */
1209 if (len
> 0 && p
[len
- 1] == '$') {
1215 /* If the first character is a '/' or '?', we just strip it. */
1216 if (len
> 0 && (p
[0] == '/' || p
[0] == '?')) {
1221 /* If the first or second character is a '^', it's magic. */
1228 * Escape every other magic character we can find, meanwhile stripping
1229 * the backslashes ctags inserts when escaping the search delimiter
1232 for (; len
> 0; --len
) {
1233 if (p
[0] == '\\' && (p
[1] == '/' || p
[1] == '?')) {
1236 } else if (strchr("^.[]$*", p
[0]))
1250 * Convert a cscope search path into something that the POSIX
1251 * 1003.2 RE functions can handle.
1254 re_cscope_conv(sp
, ptrnp
, plenp
, replacedp
)
1260 size_t blen
, len
, nspaces
;
1264 * Each space in the source line printed by cscope represents an
1265 * arbitrary sequence of spaces, tabs, and comments.
1267 #define CSCOPE_RE_SPACE "([ \t]|/\\*([^*]|\\*/)*\\*/)*"
1268 for (nspaces
= 0, p
= *ptrnp
, len
= *plenp
; len
> 0; ++p
, --len
)
1273 * Allocate plenty of space:
1274 * the string, plus potential escaping characters;
1275 * nspaces + 2 copies of CSCOPE_RE_SPACE;
1276 * ^, $, nul terminator characters.
1279 len
= (p
- *ptrnp
) * 2 + (nspaces
+ 2) * sizeof(CSCOPE_RE_SPACE
) + 3;
1280 GET_SPACE_RET(sp
, bp
, blen
, len
);
1286 memcpy(t
, CSCOPE_RE_SPACE
, sizeof(CSCOPE_RE_SPACE
) - 1);
1287 t
+= sizeof(CSCOPE_RE_SPACE
) - 1;
1289 for (len
= *plenp
; len
> 0; ++p
, --len
)
1291 memcpy(t
, CSCOPE_RE_SPACE
, sizeof(CSCOPE_RE_SPACE
) - 1);
1292 t
+= sizeof(CSCOPE_RE_SPACE
) - 1;
1294 if (strchr("\\^.[]$*+?()|{}", *p
))
1299 memcpy(t
, CSCOPE_RE_SPACE
, sizeof(CSCOPE_RE_SPACE
) - 1);
1300 t
+= sizeof(CSCOPE_RE_SPACE
) - 1;
1310 * Report a regular expression error.
1312 * PUBLIC: void re_error __P((SCR *, int, regex_t *));
1315 re_error(sp
, errcode
, preg
)
1323 s
= regerror(errcode
, preg
, "", 0);
1324 if ((oe
= malloc(s
)) == NULL
)
1325 msgq(sp
, M_SYSERR
, NULL
);
1327 (void)regerror(errcode
, preg
, oe
, s
);
1328 msgq(sp
, M_ERR
, "RE error: %s", oe
);
1335 * Do the substitution for a regular expression.
1338 re_sub(sp
, ip
, lbp
, lbclenp
, lblenp
, match
)
1340 char *ip
; /* Input line. */
1342 size_t *lbclenp
, *lblenp
;
1343 regmatch_t match
[10];
1345 enum { C_NOTSET
, C_LOWER
, C_ONELOWER
, C_ONEUPPER
, C_UPPER
} conv
;
1346 size_t lbclen
, lblen
; /* Local copies. */
1347 size_t mlen
; /* Match length. */
1348 size_t rpl
; /* Remaining replacement length. */
1349 char *rp
; /* Replacement pointer. */
1351 int no
; /* Match replacement offset. */
1352 char *p
, *t
; /* Buffer pointers. */
1353 char *lb
; /* Local copies. */
1355 lb
= *lbp
; /* Get local copies. */
1362 * There are some special sequences that vi provides in the
1363 * replacement patterns.
1364 * & string the RE matched (\& if nomagic set)
1365 * \# n-th regular subexpression
1366 * \E end \U, \L conversion
1367 * \e end \U, \L conversion
1368 * \l convert the next character to lower-case
1369 * \L convert to lower-case, until \E, \e, or end of replacement
1370 * \u convert the next character to upper-case
1371 * \U convert to upper-case, until \E, \e, or end of replacement
1373 * Otherwise, since this is the lowest level of replacement, discard
1374 * all escaping characters. This (hopefully) matches historic practice.
1376 #define OUTCH(ch, nltrans) { \
1377 CHAR_T __ch = (ch); \
1378 u_int __value = KEY_VAL(sp, __ch); \
1379 if (nltrans && (__value == K_CR || __value == K_NL)) { \
1381 sp->newl[sp->newl_cnt++] = lbclen; \
1382 } else if (conv != C_NOTSET) { \
1388 if (isupper(__ch)) \
1389 __ch = tolower(__ch); \
1395 if (islower(__ch)) \
1396 __ch = toupper(__ch); \
1407 for (rp
= sp
->repl
, rpl
= sp
->repl_len
, p
= lb
+ lbclen
; rpl
--;) {
1408 switch (ch
= *rp
++) {
1410 if (O_ISSET(sp
, O_MAGIC
)) {
1422 if (!O_ISSET(sp
, O_MAGIC
)) {
1427 case '0': case '1': case '2': case '3': case '4':
1428 case '5': case '6': case '7': case '8': case '9':
1430 subzero
: if (match
[no
].rm_so
== -1 ||
1431 match
[no
].rm_eo
== -1)
1433 mlen
= match
[no
].rm_eo
- match
[no
].rm_so
;
1434 for (t
= ip
+ match
[no
].rm_so
; mlen
--; ++t
)
1466 *lbp
= lb
; /* Update caller's information. */