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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
|
#include <sys/ioctl.h>
#include <signal.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define ARRLEN(x) (sizeof(x)/sizeof((x)[0]))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define EPRINTF(...) fprintf(stderr, __VA_ARGS__)
#define KEY_CTRL(c) (((int) (c)) & 0b11111)
#define CSI_CLEAR_LINE "\x1b[K\r"
#define CSI_CUR_HIDE "\x1b[?25l"
#define CSI_CUR_SHOW "\x1b[?25h"
#define CSI_CUR_UP "\x1b[A"
#define CSI_CUR_DOWN "\x1b[B"
#define CSI_CUR_RIGHT "\x1b[C"
#define CSI_CUR_LEFT "\x1b[D"
#define CSI_STYLE_BOLD "\x1b[1m"
#define CSI_STYLE_RESET "\x1b[0m"
#define CSI_CLEAR_SCREEN "\x1b[2J"
#define CSI_STYLE_ULINE "\x1b[4m"
#define CSI_STYLE_NULINE "\x1b[24m"
#define CSI_CUR_GOTO "\x1b[%i%iH"
enum {
BWD = -1,
FWD = 1,
};
enum {
MODE_BROWSE,
MODE_SEARCH,
};
enum {
SEARCH_SUBSTR,
SEARCH_FUZZY,
};
enum {
CASE_SENSITIVE,
CASE_INSENSITIVE,
};
enum {
KEY_NONE = 0,
KEY_DEL = 0x7f,
KEY_UP = 0x100,
KEY_DOWN,
KEY_LEFT,
KEY_RIGHT,
KEY_PGUP,
KEY_PGDN,
};
struct mode {
void (*prompt)(void);
void (*cleanup)(void);
bool (*handlekey)(int c);
};
struct searchmode {
char c;
ssize_t (*match)(ssize_t, int, size_t, ssize_t, bool, bool);
};
struct entry {
size_t full;
size_t visible;
};
static void browse_prompt(void);
static bool browse_handlekey(int c);
static void browse_cleanup(void);
static void search_prompt(void);
static bool search_handlekey(int c);
static void search_cleanup(void);
static ssize_t search_match(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest);
static ssize_t search_match_substr(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest);
static ssize_t search_match_fuzzy(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest);
static const struct searchmode searchmodes[] = {
[SEARCH_SUBSTR] = {
.c = 'S',
.match = search_match_substr,
},
[SEARCH_FUZZY] = {
.c = 'F',
.match = search_match_fuzzy,
}
};
static const struct mode modes[] = {
[MODE_BROWSE] = {
.prompt = browse_prompt,
.handlekey = browse_handlekey,
.cleanup = browse_cleanup
},
[MODE_SEARCH] = {
.prompt = search_prompt,
.handlekey = search_handlekey,
.cleanup = search_cleanup
}
};
static bool init = false;
static char *input = NULL;
static size_t input_len = 0;
static size_t input_cap = 0;
static struct entry *entries = NULL;
static size_t entries_len = 0;
static size_t entries_cap = 0;
static size_t entries_cnt = 0;
static ssize_t selected = -1;
static const char *entry = NULL;
static size_t entry_off = 0;
static char searchbuf[1024];
static size_t searchlen = 0;
static int mode = MODE_BROWSE;
static int searchcase = CASE_SENSITIVE;
static int searchmode = SEARCH_SUBSTR;
static size_t fwdctx = 1;
static size_t bwdctx = 1;
static size_t termw = 80;
static bool multiout = false;
static bool verbose = false;
static bool show_prompt = true;
static bool top_prompt = false;
static char delim = '\n';
static char vis_delim = '|';
static void
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fputs("tmenu: ", stderr);
vfprintf(stderr, fmt, ap);
if (*fmt && fmt[strlen(fmt) - 1] == ':') {
fputc(' ', stderr);
perror(NULL);
} else {
fputc('\n', stderr);
}
va_end(ap);
exit(1);
}
static void
prompt(void)
{
struct winsize ws = { 0 };
if (ioctl(2, TIOCGWINSZ, &ws) != -1)
termw = ws.ws_col;
modes[mode].prompt();
}
static void
sigwinch(int sig)
{
if (init) prompt();
signal(SIGWINCH, sigwinch);
}
static void *
addcap(void *alloc, size_t dsize, size_t min, size_t *cap)
{
if (min > *cap) {
*cap = *cap * 2;
if (*cap < min) *cap = min;
alloc = realloc(alloc, dsize * *cap);
if (!alloc) die("realloc:");
}
return alloc;
}
static inline char
lower(char c)
{
if (c >= 'A' && c <= 'Z')
c += 'a' - 'A';
return c;
}
static size_t
vis_entry_len(size_t index)
{
if (index == entries_cnt-1)
return input_len - entries[index].visible;
return entries[index+1].visible-1 - entries[index].visible;
}
static inline char *
vis_entry(size_t index)
{
return input + entries[index].visible;
}
static inline char *
full_entry(size_t index)
{
return input + entries[index].full;
}
static int
readkey(FILE *f)
{
int c;
c = fgetc(f);
if (c != '\x1b')
return c;
if (fgetc(f) != '[')
return KEY_NONE;
switch (fgetc(f)) {
case 'A':
return KEY_UP;
case 'B':
return KEY_DOWN;
case 'C':
return KEY_RIGHT;
case 'D':
return KEY_LEFT;
case '5':
return fgetc(f) == '~' ? KEY_PGUP : KEY_NONE;
case '6':
return fgetc(f) == '~' ? KEY_PGDN : KEY_NONE;
}
return KEY_NONE;
}
static int
search_eq(const char *a, const char *b, size_t size)
{
size_t i;
for (i = 0; i < size; i++) {
if (searchcase == CASE_SENSITIVE) {
if (a[i] != b[i]) return false;
} else {
if (lower(a[i]) != lower(b[i]))
return false;
}
}
return true;
}
static const char*
search_find(const char *a, char c, size_t size)
{
size_t i;
for (i = 0; i < size; i++) {
if (searchcase == CASE_SENSITIVE) {
if (a[i] == c) return a + i;
} else if (searchcase == CASE_INSENSITIVE) {
if (lower(a[i]) == lower(c))
return a + i;
}
}
return NULL;
}
static void
browse_prompt(void)
{
size_t linew, entlen;
ssize_t i;
if (selected < 0) selected = 0;
if (show_prompt && top_prompt)
EPRINTF(CSI_STYLE_BOLD "[B] " CSI_STYLE_RESET "\n");
i = (ssize_t) selected - (ssize_t) bwdctx;
for (; i <= (ssize_t) selected + (ssize_t) fwdctx; i++) {
EPRINTF(CSI_CLEAR_LINE);
if (i == selected)
EPRINTF(CSI_STYLE_BOLD);
if (show_prompt && !top_prompt) {
linew = termw - 4;
if (i == selected) {
EPRINTF("[B] ");
} else {
EPRINTF(" ");
}
} else {
linew = termw;
}
if (selected >= 0 && i >= 0 && i < entries_cnt) {
entry = vis_entry((size_t) i);
entlen = vis_entry_len((size_t) i);
if (entlen > linew) {
EPRINTF(" ..%.*s\n", (int) (linew - 3),
entry + entlen - (linew - 3));
} else {
EPRINTF("%.*s\n", (int) linew, entry);
}
} else {
EPRINTF("\n");
}
if (i == selected)
EPRINTF(CSI_STYLE_RESET);
}
for (i = 0; i < bwdctx + fwdctx + 1 + show_prompt * top_prompt; i++)
EPRINTF(CSI_CUR_UP);
}
static bool
browse_handlekey(int c)
{
size_t cnt;
switch (c) {
case 'g':
selected = 0;
break;
case 'G':
selected = (ssize_t) entries_cnt - 1;
break;
case 'q':
return true;
case KEY_PGUP:
cnt = fwdctx + bwdctx + 1;
if (selected > cnt)
selected -= (ssize_t) cnt;
else
selected = 0;
break;
case KEY_PGDN:
cnt = fwdctx + bwdctx + 1;
if (selected < entries_cnt - cnt)
selected += (ssize_t) cnt;
else
selected = (ssize_t) entries_cnt - 1;
break;
case KEY_UP:
if (selected != 0)
selected--;
break;
case KEY_DOWN:
if (selected != entries_cnt - 1)
selected++;
break;
}
return false;
}
static void
browse_cleanup(void)
{
size_t i;
for (i = 0; i < bwdctx + 1 + fwdctx; i++)
EPRINTF(CSI_CLEAR_LINE "\n");
for (i = 0; i < bwdctx + 1 + fwdctx; i++)
EPRINTF(CSI_CUR_UP);
}
static void
search_prompt(void)
{
size_t linew, off, entlen;
ssize_t i, index;
if (selected < 0) selected = 0;
index = search_match(selected, FWD, 1, -1, false, true);
if (index != -1) {
selected = index;
} else {
selected = search_match(selected, BWD, 1, -1, true, true);
}
if (show_prompt && top_prompt) {
EPRINTF(CSI_STYLE_BOLD "[%c] " CSI_STYLE_ULINE "%.*s"
CSI_STYLE_NULINE "%.*s\n" CSI_STYLE_RESET,
(searchcase == CASE_SENSITIVE ?
searchmodes[searchmode].c
: lower(searchmodes[searchmode].c)),
(int) searchlen, searchbuf, (int) termw, " ");
}
for (i = -(ssize_t) bwdctx; i <= (ssize_t) fwdctx; i++) {
if (selected >= 0) {
if (i < 0) {
index = search_match(selected,
BWD, (size_t) -i, -1, true, false);
} else if (i == 0) {
index = selected;
} else if (i > 0) {
index = search_match(selected,
FWD, (size_t) i, -1, true, false);
}
} else {
index = -1;
}
EPRINTF(CSI_CLEAR_LINE);
if (i == 0) EPRINTF(CSI_STYLE_BOLD);
if (show_prompt && !top_prompt) {
if (i == 0) {
EPRINTF("[%c] " CSI_STYLE_ULINE "%.*s"
CSI_STYLE_NULINE " ",
(searchcase == CASE_SENSITIVE ?
searchmodes[searchmode].c
: lower(searchmodes[searchmode].c)),
(int) searchlen, searchbuf);
} else {
EPRINTF("%*.s", (int) (4 + searchlen + 1), " ");
}
linew = (size_t) MAX(0, (ssize_t) termw
- (ssize_t) searchlen - 5);
} else {
linew = termw;
}
if (index < 0) {
EPRINTF("\n");
} else {
entlen = vis_entry_len((size_t) index);
entry = vis_entry((size_t) index);
off = entlen >= linew ? entlen - linew : 0;
off = MIN(entry_off, off);
EPRINTF("%.*s\n", (int) linew, entry + off);
}
if (i == 0) EPRINTF(CSI_STYLE_RESET);
}
for (i = 0; i < bwdctx + fwdctx + 1 + show_prompt * top_prompt; i++)
EPRINTF(CSI_CUR_UP);
}
static bool
search_handlekey(int c)
{
size_t cnt;
switch (c) {
case KEY_CTRL('I'):
searchcase ^= 1;
break;
case KEY_PGUP:
cnt = fwdctx + bwdctx + 1;
selected = search_match(selected, BWD, cnt, selected, true, true);
break;
case KEY_PGDN:
cnt = fwdctx + bwdctx + 1;
selected = search_match(selected, FWD, cnt, selected, true, true);
break;
case KEY_CTRL('K'):
case KEY_UP:
selected = search_match(selected, BWD, 1, selected, true, true);
break;
case KEY_CTRL('L'):
case KEY_DOWN:
selected = search_match(selected, FWD, 1, selected, true, true);
break;
case 0x20 ... 0x7e:
if (searchlen < sizeof(searchbuf) - 1)
searchbuf[searchlen++] = (char) (c & 0xff);
break;
case KEY_DEL:
if (searchlen) searchlen--;
break;
}
return false;
}
static void
search_cleanup(void)
{
size_t i;
for (i = 0; i < bwdctx + 1 + fwdctx; i++)
EPRINTF(CSI_CLEAR_LINE "\n");
for (i = 0; i < bwdctx + 1 + fwdctx; i++)
EPRINTF(CSI_CUR_UP);
}
static ssize_t
search_match(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest)
{
return searchmodes[searchmode].match(start, dir,
cnt, fallback, new, closest);
}
static ssize_t
search_match_linear(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest)
{
ssize_t index;
index = start + dir * (ssize_t) (new + cnt - 1);
if (index < 0) return closest ? 0 : fallback;
if (index >= entries_cnt)
return closest ? (ssize_t) entries_cnt - 1 : fallback;
return index;
}
static ssize_t
search_match_substr(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest)
{
const char *end, *bp;
size_t i, found;
ssize_t index, prev;
if (!searchlen)
return search_match_linear(start, dir,
cnt, fallback, new, closest);
prev = -1;
found = 0;
for (i = new; i < entries_cnt; i++) {
index = start + dir * (ssize_t) i;
if (index < 0 || index >= entries_cnt)
break;
entry = vis_entry((size_t) index);
end = entry + vis_entry_len((size_t) index);
for (bp = entry; *bp; bp++) {
if (searchlen > end - bp) continue;
if (search_eq(bp, searchbuf, searchlen)) {
if (++found == cnt)
return index;
prev = index;
break;
}
}
}
return closest ? prev : fallback;
}
static ssize_t
search_match_fuzzy(ssize_t start, int dir,
size_t cnt, ssize_t fallback, bool new, bool closest)
{
const char *end, *pos, *c;
size_t i, found;
ssize_t index, prev;
if (!searchlen)
return search_match_linear(start, dir,
cnt, fallback, new, closest);
prev = -1;
found = 0;
for (i = new; i < entries_cnt; i++) {
index = start + dir * (ssize_t) i;
if (index < 0 || index >= entries_cnt)
break;
entry = vis_entry((size_t) index);
end = entry + vis_entry_len((size_t) index);
pos = entry;
for (c = searchbuf; c - searchbuf < searchlen; c++) {
pos = search_find(pos, *c, (size_t) (end - pos));
if (!pos) break;
pos++;
}
if (c == searchbuf + searchlen) {
if (++found == cnt)
return index;
prev = index;
}
}
return closest ? prev : fallback;
}
static void
load(int fd)
{
ssize_t nread;
size_t i;
char *c;
if (!entries_cap)
entries = addcap(entries, sizeof(struct entry), 1, &entries_cap);
if (!entries_len) {
entries[0].full = 0;
entries[0].visible = 0;
entries_len = 1;
}
while (1) {
input = addcap(input, 1, input_len + BUFSIZ + 1, &input_cap);
nread = read(fd, input + input_len, BUFSIZ);
if (nread <= 0) break;
c = input + input_len;
for (i = input_len; i < input_len + (size_t) nread; i++, c++) {
if (*c == vis_delim) {
entries[entries_len-1].visible = i + 1;
} else if (*c == delim) {
*c = '\0';
entries = addcap(entries, sizeof(struct entry),
entries_len + 1, &entries_cap);
entries[entries_len].full = i + 1;
entries[entries_len].visible = i + 1;
entries_len++;
}
}
input_len += (size_t) nread;
}
input[input_len] = '\0';
entries_cnt = 0;
if (entries_len) {
if (input_len <= entries[entries_len-1].full)
entries_cnt = entries_len-1;
else
entries_cnt = entries_len;
}
if (verbose)
EPRINTF("Loaded %lu entries\n", entries_cnt);
}
static void
run(void)
{
struct termios prevterm, newterm = { 0 };
int c;
if (!entries_cnt) return;
if (tcgetattr(0, &prevterm))
die("tcgetattr:");
cfmakeraw(&newterm);
newterm.c_oflag |= ONLCR | OPOST;
if (tcsetattr(0, TCSANOW, &newterm))
die("tcsetattr:");
EPRINTF(CSI_CUR_HIDE);
init = true;
selected = 0;
searchlen = 0;
do {
prompt();
switch ((c = readkey(stdin))) {
case KEY_CTRL('C'):
goto exit;
case KEY_CTRL('D'):
if (!multiout) goto exit;
break;
case KEY_CTRL('S'):
searchmode = SEARCH_SUBSTR;
mode = MODE_SEARCH;
break;
case KEY_CTRL('F'):
searchmode = SEARCH_FUZZY;
mode = MODE_SEARCH;
break;
case KEY_CTRL('Q'):
case KEY_CTRL('B'):
mode = MODE_BROWSE;
break;
case KEY_CTRL('L'):
EPRINTF(CSI_CLEAR_SCREEN CSI_CUR_GOTO, 0, 0);
break;
case KEY_CTRL('W'):
searchlen = 0;
break;
case KEY_CTRL('J'):
case '\r':
if (selected < 0) break;
entry = full_entry((size_t) selected);
modes[mode].cleanup();
puts(entry);
if (!multiout) goto exit;
break;
default:
if (modes[mode].handlekey(c))
goto exit;
break;
}
} while (c >= 0);
exit:
modes[mode].cleanup();
EPRINTF(CSI_CUR_SHOW);
tcsetattr(fileno(stdin), TCSANOW, &prevterm);
}
static int
parseopt(const char *flag, const char **args)
{
char *end;
if (flag[0] && flag[1]) {
EPRINTF("Invalid flag: -%s\n", flag);
exit(1);
}
switch (flag[0]) {
case 'm':
multiout = true;
return 0;
case 'v':
verbose = true;
return 0;
case 's':
mode = MODE_SEARCH;
searchmode = SEARCH_SUBSTR;
return 0;
case 'n':
show_prompt = false;
return 0;
case 'a':
if (!*args) die("missing -a arg");
fwdctx = strtoull(*args, &end, 10);
if (end && *end) die("bad -a arg '%s'", *args);
return 1;
case 'b':
if (!*args) die("missing -b arg");
bwdctx = strtoull(*args, &end, 10);
if (end && *end) die("bad -b arg '%s'", *args);
return 1;
case 'c':
if (!*args) die("missing -c arg");
fwdctx = bwdctx = strtoull(*args, &end, 10);
if (end && *end) die("bad -c arg '%s'", *args);
return 1;
case 'd':
if (!*args) die("missing -d arg");
if (args[0][0] && args[0][1]) die("bad -d arg");
delim = **args;
return 1;
case 'D':
if (!*args) die("missing -d arg");
if (args[0][0] && args[0][1]) die("bad -d arg");
vis_delim = **args;
return 1;
case 't':
top_prompt = true;
return 0;
case 'h':
printf("Usage: tmenu [-h] [-m] [-d DELIM] [-D DELIM] [-a LINES] [-b LINES]");
exit(0);
default:
die("unknown opt '%s'", *flag);
}
return 0;
}
int
main(int argc, const char **argv)
{
const char **arg;
int fd;
signal(SIGWINCH, sigwinch);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
for (arg = argv + 1; *arg; arg++) {
if (**arg == '-') {
arg += parseopt(*arg + 1, arg + 1);
} else {
fd = open(*arg, O_RDONLY);
if (fd < 0) die("open '%s':", *arg);
load(fd);
close(fd);
}
}
if (!input) {
load(0);
if (!freopen("/dev/tty", "r", stdin))
die("freopen tty:");
}
run();
}
|