commit 21447b74b0de70994727e99254f4290c3d02d173
parent 74e966a35d5c673629afe47a1b79adba1aa9ddbf
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date: Sat, 12 Dec 2015 18:16:41 +0100
Add subline()
This is a first implementation of subline, which applies
the current substition to a line.
Diffstat:
M | ed.c | | | 75 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------- |
1 file changed, 65 insertions(+), 10 deletions(-)
diff --git a/ed.c b/ed.c
@@ -829,24 +829,79 @@ getrhs(int delim)
s = NULL;
}
+static int
+getnth(void)
+{
+ int c;
+
+ if ((c = input()) == 'g') {
+ return -1;
+ } else if (isdigit(c)) {
+ return c - '0';
+ } else {
+ back(c);
+ return 1;
+ }
+}
+
+static void
+subline(int num, int nth)
+{
+ char *s, *p, *t, c, *q;
+ size_t siz, cap;
+ static char *line;
+ regmatch_t m[10], *mp;
+
+ free(line);
+ line = NULL;
+
+ p = s = gettxt(num);
+ while (nth--) {
+ if (!regexec(pattern, s, 10, m, 0))
+ return;
+ p += m[0].rm_eo;
+ if (nth <= 0)
+ break;
+ }
+
+ siz = cap = 0;
+ for (t = s; p > t; ++t)
+ line = addchar(*t++, line, &cap, &siz);
+
+ for (t = rhs; c = *t; ++t) {
+ switch (c) {
+ case '\\':
+ if (!isdigit(*t))
+ goto add_char;
+ mp = &m[*t++ - '0'];
+ goto add_string;
+ case '&':
+ mp = &m[0];
+ add_string:
+ for (q = s + mp->rm_so; q < s + mp->rm_eo; ++q)
+ line = addchar(*q, line, &cap, &siz);
+ break;
+ default:
+ add_char:
+ line = addchar(c, line, &cap, &siz);
+ break;
+ }
+ }
+}
+
static void
subs(void)
{
- int c, delim;
- int gsub;
+ int delim, nth, i;
+ char *s;
delim = input();
compile(delim);
getrhs(delim);
+ nth = getnth();
- if ((c = input()) == 'g') {
- gsub = -1;
- } else if (isdigit(c)) {
- gsub = c - '0';
- } else {
- gsub = 1;
- back(c);
- }
+ for (i = line1; i <= line2; i = nextln(i))
+ subline(i, nth);
}
static void