From 533fd864a564943beba3b0d311eb7e0f990051e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= Date: Sat, 12 Dec 2020 20:33:55 +0100 Subject: typ.c: Add backspace support (draft) --- typ.c | 51 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/typ.c b/typ.c index 542476d..8c6d808 100644 --- a/typ.c +++ b/typ.c @@ -23,41 +23,72 @@ int main() { wt = malloc(ws * sizeof(double)); /* word times */ if (wt == NULL) err(1, "malloc"); + for (int i = 0; i < ws; i++) + wt[i] = 0; + l = 0; /* current word length */ - wi = 0; /* number of current word in order */ + wi = -1; /* index of current word in order */ /* enter "raw" mode */ ttyfd = open("/dev/tty", O_RDWR); if (ttyfd == -1) err(1, "open"); tcgetattr(ttyfd, &orig); raw = orig; - raw.c_lflag &= ~(ICANON); + raw.c_lflag &= ~(ECHO | ICANON); tcsetattr(ttyfd, TCSANOW, &raw); /* read loop */ - while ((c = getchar()) != EOF) { - if (l == 0) - t = atime(); /* current word time */ + while (read(ttyfd, &c, 1)) { + /* backspace */ + if (c == 127) { + l--; + write(ttyfd, &c, 1); + if (l == -1) { + wi--; + fprintf(stderr, "<\n"); + } + continue; + } + + /* back to previous word (after backspace) */ + if (l == -1) { + l = wl[wi]; + fprintf(stderr, "%d\n", wl[wi-1]); + } + + /* new word */ + if (c != ' ' && c != '\n' && (l == 0 || l == -1)) { + wi++; + t = atime(); /* current word start time */ + fprintf(stderr, "*\n"); + } + + /* end word */ if (c == ' ' || c == '\n') { wl[wi] = l; - wt[wi] = atime() - t; + if (t > -1) { + wt[wi] += atime() - t; + // fprintf(stderr, "[+%f]", atime() - t); + } l = 0; - wi++; + t = -1; } else l++; if (c == '\n') break; + write(ttyfd, &c, 1); } + write(ttyfd, "\n", 1); /* print statistics */ double tt = 0; int tl = 0; - for (int i = 0; i < wi; i++) { + for (int i = 0; i <= wi; i++) { tt += wt[i]; tl += wl[i]; } - printf("%f seconds per word\n", tt / wi); - printf("%f seconds per word character\n", tt / tl); + printf("%f seconds per word (%d)\n", tt / (wi + 1), wi + 1); + printf("%f seconds per word character (%d)\n", tt / tl, tl); /* restore original terminal settings */ tcsetattr(ttyfd, TCSANOW, &orig); -- cgit v1.2.3