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
|
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "doc.h"
#include "err.h"
#include "nav.h"
/* pagination */
/* navigation */
/* commands */
struct cmd {
char ch;
int (*fn)(const char *);
};
/* cmd is mutated when trimming strings
* returns whether to quit */
int cmd_do(char *cmd, struct nav_state *ns) {
switch (*cmd) {
case 'q':
puts("goodbye!");
return 1;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
errno = 0;
unsigned long n = strtoul(cmd, NULL, 10);
if (errno) {
perr("invalid link number");
} else if (nav_link_nr(ns, n)) {
perr("navigation failure");
}
}
break;
case 'b':
nav_pg_up(ns);
break;
case '\0':
nav_pg_down(ns);
break;
case 'r':
nav_redraw(ns);
break;
case 'g':
if (nav_to(ns, cmd + 1)) perr("navigation failure");
break;
case 'p':
nav_prev(ns);
break;
case 'n':
nav_next(ns);
break;
default:
perr("?");
break;
}
return 0;
}
void cmd_trim(char *buf, size_t max) {
size_t n = strlen(buf);
while (n > 0 && isspace(buf[n - 1])) {
buf[--n] = 0;
}
while (n > 1 && isspace(buf[1])) {
memmove(&buf[0], &buf[1], n--);
}
}
int cmd_get(char *buf, size_t n) {
fputs("* ", stdout);
return !!fgets(buf, n, stdin);
}
int main(void) {
struct nav_state ns;
char cmd_buf[1024];
nav_init(&ns);
while (cmd_get(cmd_buf, sizeof cmd_buf)) {
cmd_trim(cmd_buf, sizeof cmd_buf);
if (cmd_do(cmd_buf, &ns)) {
break;
}
}
nav_fini(&ns);
return 0;
}
|