-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubst.c
115 lines (105 loc) · 2.35 KB
/
subst.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* subst -- substitute "sub" for occurrences of pattern */
#include <stdio.h>
#include "edit.h"
#include "editdefs.h"
int getrhs( char *line, int *i, char *sub, int *gflag);
static void catsub(char *line, int s1, int s2, char *sub, char *new, int *k, int maxnew);
static int makesub(char *arg, int from, char delim, char *sub);
int
subst(char *sub, int gflag, int glob)
{
char old[MAXSTR], new[MAXSTR];
int j, k, lastm, line, m, stat, done, subbed;
stat = (glob? OK: ERR);
done = (line1 <= 0);
line = line1;
while (!done && line <= line2) { /* do subst from line1 to line2 */
j = 0;
subbed = FALSE;
gettxt(line, old);
lastm = 0;
k = 0;
while (old[k] != '\0') {
if (gflag || !subbed)
m = amatch(old, k, pat, 0);
else
m = 0;
if (m > 0 && lastm != m) { /* replace matched text */
subbed = TRUE;
catsub(old, k, m, sub, new, &j, MAXSTR);
lastm = m;
}
if (m == 0 || m == k) /* no match or null match */
addstr(old[k++], new, &j, MAXSTR);
else /* skip matched text */
k = m;
}
if (subbed) {
if (!addstr('\0', new, &j, MAXSTR)) {
stat = error("substitute too big", NULL);
done = TRUE;
}
else {
stat = lndelete(line, line);
stat = puttxt(new);
line2 += curln - line;
line = curln;
if (stat == ERR)
done = TRUE;
else
stat = OK;
}
}
++line;
}
return stat;
}
/* getrhs -- get right hand side of "s" command */
int
getrhs(char *line, int *i, char *sub, int *gflag)
{
if (line[*i] == '\0' || line[*i+1] == '\0')
return ERR;
*i = makesub(line, *i+1, line[*i], sub);
if (*i == 0)
return ERR;
else if (line[*i+1] == 'g') {
++*i;
*gflag = TRUE;
}
else
*gflag = FALSE;
return OK;
}
/* makesub -- make substitution string from arg into sub */
int
makesub(char *arg, int from, char delim, char *sub)
{
int i, j = 0;
i = from;
while (arg[i] != delim && arg[i] != '\0') {
if (arg[i] == '&')
addstr(DITTO, sub, &j, MAXPAT);
else
addstr(esc(arg, &i), sub, &j, MAXPAT);
++i;
}
if (arg[i] != delim) /* missing delimiter */
i = 0;
else if (!addstr('\0', sub, &j, MAXPAT))
i = 0;
return i;
}
void
catsub(char *line, int s1, int s2, char *sub, char *new, int *k, int maxnew)
{
int i = 0, j;
while (sub[i]) {
if (sub[i] == DITTO)
for (j = s1; j < s2; j++)
addstr(line[j], new, k, maxnew);
else
addstr(sub[i], new, k, maxnew);
++i;
}
}