aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Ankarström <john@ankarstrom.se>2020-12-12 20:33:55 +0100
committerJohn Ankarström <john@ankarstrom.se>2020-12-12 20:33:55 +0100
commit533fd864a564943beba3b0d311eb7e0f990051e2 (patch)
treee9ad8259a4e0dabffc55be8533051ff24ced0993
parent119904b4ecd8684e27db5af54e8f42082749324f (diff)
downloadtyp-533fd864a564943beba3b0d311eb7e0f990051e2.tar.gz
typ.c: Add backspace support (draft)
-rw-r--r--typ.c51
1 files 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);