File: urlview.c

package info (click to toggle)
urlview 1e-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 276 kB
  • sloc: ansic: 876; cpp: 295; sh: 119; makefile: 82
file content (901 lines) | stat: -rw-r--r-- 27,371 bytes parent folder | download
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 1997 Michael R. Elkins <me@cs.hmc.edu>
// Created:       Thu Dec  4 02:13:11 PST 1997
// Last Modified: Tue Jul  4 11:23:49 CEST 2000


#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <locale.h>
#include <ncurses.h>
#include <regex.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ttydefaults.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#if __has_include(<libintl.h>)
#include <libintl.h>
#else
#define gettext(s) (s)
#define ngettext(s, p, n) (n == 1 ? s : p)
#endif

#include "enter.h"
#include "quote.h"
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define auto __auto_type
#ifndef REG_STARTEND
#define REG_STARTEND_OPT 0
#else
#define REG_STARTEND_OPT REG_STARTEND
#endif


enum redraw { FULL, INDEX, MOTION, CURSORPOS, NO };
struct url {
	char * url;
	size_t urllen;
	int cursor_y, cursor_x;
	int last_y;
};

static char * regex_error(const regex_t * rx, int err) {
	size_t es = regerror(err, rx, NULL, 0);
	char * eb = malloc(es);
	if(eb)
		regerror(err, rx, eb, es);
	return eb;
}

static void search_common(const char * search, regex_t * rx, size_t urlcount, struct url * url, enum redraw * redraw, size_t * current,
                          bool (*matcher)(const regex_t * rx, size_t urlcount, struct url * url, size_t * current)) {
	if(search) {
		regex_t newrx;
		int regerr = regcomp(&newrx, search, REG_EXTENDED | REG_ICASE | REG_NOSUB);
		if(regerr) {
			char * err = regex_error(&newrx, regerr);
			mvaddstr(LINES - 1, 0, search);
			addstr(": ");
			addstr(err ?: "?");
			clrtoeol();
			free(err);
			*redraw = CURSORPOS;
			return;
		}

		if(rx->re_nsub != (size_t)-1)
			regfree(rx);
		*rx = newrx;
	}

	if(matcher(rx, urlcount, url, current)) {
		move(LINES - 1, 0);
		*redraw = MOTION;
	} else {
		// as in "no search results", p.a. to "No such URL!"; potentially displayed after "Search [forwards/backwards] for:"
		mvaddstr(LINES - 1, 0, gettext("No matches!"));
		*redraw = CURSORPOS;
	}
	clrtoeol();
}

static bool search_impl(const regex_t * rx, struct url * url) {
	return !regexec(rx, url->url, 0, &(regmatch_t){.rm_so = 0, .rm_eo = url->urllen}, REG_STARTEND_OPT);
}

static bool search_forward(const regex_t * rx, size_t urlcount, struct url * url, size_t * current) {
	for(size_t i = *current + 1; i < urlcount; ++i)
		if(search_impl(rx, &url[i])) {
			*current = i;
			return true;
		}
	return false;
}

static bool search_backward(const regex_t * rx, size_t urlcount, struct url * url, size_t * current) {
	(void)urlcount;

	for(size_t i = *current - 1; i != (size_t)-1; --i)
		if(search_impl(rx, &url[i])) {
			*current = i;
			return true;
		}
	return false;
}

static void writev_all(int fd, struct iovec * iovs, size_t iovs_cnt) {
	struct sigaction pipe;
	sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, &pipe);
	for(ssize_t wr; iovs_cnt;) {
		while((wr = writev(fd, iovs, iovs_cnt)) == -1 && errno == EINTR)
			;
		if(wr == -1)
			break;

		while(wr) {
			size_t min = MIN((size_t)wr, iovs[0].iov_len);
			iovs[0].iov_base += min;
			iovs[0].iov_len -= min;
			if(!iovs[0].iov_len)
				++iovs, --iovs_cnt;
			wr -= min;
		}
	}
	sigaction(SIGPIPE, &pipe, NULL);
}

enum via { ARGUMENT, ENVIRONMENT, PIPE };
// if ARGUMENT, program must have already been pre-processed
static int system_via(const char * program, const char * url, enum via via) {
	struct sigaction intr, quit;
	sigaction(SIGINT, &(struct sigaction){.sa_handler = SIG_IGN}, &intr);
	sigaction(SIGQUIT, &(struct sigaction){.sa_handler = SIG_IGN}, &quit);

	int pfd[2];
	if(via == PIPE)
		if(pipe2(pfd, O_CLOEXEC) == -1)
			return -1;

	pid_t pid = fork();
	switch(pid) {
		case -1:
			return -1;
		case 0:  // child
			sigaction(SIGINT, &intr, NULL);
			sigaction(SIGQUIT, &quit, NULL);
			switch(via) {
				case ARGUMENT:
					break;
				case ENVIRONMENT:
					setenv("URL", url, true);
					break;
				case PIPE:
					dup2(pfd[0], 0);
					break;
			}
			execl("/bin/sh", "sh", "-c", "--", program, (char *)NULL);
			_exit(errno == ENOENT ? 127 : 126);
	}

	if(via == PIPE) {
		close(pfd[0]);
		struct iovec iovs[2] = {{.iov_base = (void *)url, .iov_len = strlen(url)}, {.iov_base = "\n", .iov_len = 1}};
		writev_all(pfd[1], iovs, 2);
		close(pfd[1]);
	}

	int status;
	while(waitpid(pid, &status, 0) == -1)  // EINTR
		;
	sigaction(SIGINT, &intr, NULL);
	sigaction(SIGINT, &quit, NULL);
	return status;
}

int main(int argc, char ** argv) {
	setlocale(LC_ALL, "");
#if __has_include(<libintl.h>)
	bindtextdomain("urlview-ng", TEXTDOMAIN_DIRNAME);
	textdomain("urlview-ng");
#endif

	/*** read the initialization file ***/
	char * command     = NULL;
	char * regexp      = NULL;
	bool expert        = false;
	bool skip_browser  = false;
	bool menu_wrapping = false;
	bool edit_url      = false;
	bool mouse         = true;
	enum via via       = ARGUMENT;
	char * xselection  = NULL;

	FILE * fp   = NULL;
	char * home = getenv("HOME");
	if(home) {
		char * fpp;
		if(asprintf(&fpp, "%s/.urlview", home) != -1) {
			fp = fopen(fpp, "re");
			free(fpp);
		}
	}
	if(!fp)
		fp = fopen(SYSTEM_INITFILE, "re");

	char * line    = NULL;
	size_t linecap = 0;
	if(fp) {
		for(ssize_t len; (len = getline(&line, &linecap, fp)) != -1;) {
			if(line[0] == '#' || line[0] == '\n')
				continue;
			if(line[len - 1] == '\n')
				line[--len] = '\0';

			size_t keylen   = strcspn(line, " \f\n\r\t\v");
			size_t seplen   = strspn(line + keylen, " \f\n\r\t\v");
			char * key      = line;
			char * value    = line + keylen + seplen;
			size_t valuelen = len - (keylen + seplen);

#define BOOLKEY(name, var)                                                                                                                                  \
	if(KEYMATCH(name)) {                                                                                                                                      \
		if(!strcasecmp("YES", value))                                                                                                                           \
			var = true;                                                                                                                                           \
		else if(!strcasecmp("NO", value))                                                                                                                       \
			var = false;                                                                                                                                          \
		else /* "BROWSER", user's input, "yes, no" */                                                                                                           \
			errx(1, gettext("Unknown value for %s: %s. Valid values are: %s."), name, value, /* leave yes/no intact, but add explanations */ gettext("yes, no")); \
	}

#define KEYMATCH(k) keylen == sizeof(k) - 1 && !memcmp(key, k, sizeof(k) - 1)
			if(KEYMATCH("REGEXP") && valuelen) {
				if(!(regexp = realloc(regexp, valuelen)))
					err(1, NULL);
				char * wc = regexp;
				while(*value) {
					if(*value == '\\') {
						value++;
						switch(*value) {
							case 'n':
								*wc++ = '\n';
								break;
							case 'r':
								*wc++ = '\r';
								break;
							case 't':
								*wc++ = '\t';
								break;
							case 'f':
								*wc++ = '\f';
								break;
							default:
								*wc++ = '\\';
								*wc++ = *value;
								break;
						}
					} else
						*wc++ = *value;
					++value;
				}
				*wc = '\0';
			} else if(KEYMATCH("COMMAND") && valuelen) {
				free(command);
				if(!(command = strdup(value)))
					err(1, NULL);
				skip_browser = true;
			} else if(KEYMATCH("XSELECTION") && valuelen) {
				free(xselection);
				if(asprintf(&xselection, "--%s", value) == -1)
					err(1, NULL);
			} else
				BOOLKEY("WRAP", menu_wrapping)
			else                           //
			    BOOLKEY("EDIT", edit_url)  //
			    else                       //
			    BOOLKEY("MOUSE", mouse)    //
			    else if(KEYMATCH("VIA")) {
				if(!strcasecmp("ARGUMENT", value))
					via = ARGUMENT;
				else if(!strcasecmp("ENVIRONMENT", value))
					via = ENVIRONMENT;
				else if(!strcasecmp("PIPE", value))
					via = PIPE;
				else /* "VIA", user's input, "argument, environment, pipe" */
					errx(1, gettext("Unknown value for %s: %s. Valid values are: %s."), "VIA", value,
					     /*leave argument/environment/pipe intact, but add explanations*/ gettext("argument, environment, pipe"));
			}
			else if(KEYMATCH("BROWSER"))  //
			    skip_browser = false;
			else if(KEYMATCH("EXPERT"))  //
			    expert = true;
			else  //
			    errx(1, gettext("Unknown setting: %s"), line);
		}
		fclose(fp);
	}
	if(!xselection)
		xselection = (char *)"--primary";

	/* Only use the $BROWSER environment variable if
	 * (a) no COMMAND in rc file or
	 * (b) BROWSER in rc file.
	 * If both COMMAND and BROWSER are in the rc file, then the option used
	 * last counts.
	 */
	if(!skip_browser) {
		char * browser = getenv("BROWSER");
		if(browser) {
			if(*browser)
				command = browser;
			else
				warnx(gettext("Empty $BROWSER, falling back to COMMAND (%s)."), command ?: DEFAULT_COMMAND);
		}
	}
	if(!command)
		command = (char *)DEFAULT_COMMAND;

	if(via == ARGUMENT && !expert && strchr(command, '\''))
		errx(1, gettext("\n"
		                "Your COMMAND/$BROWSER contains a single quote (') character.\n"
		                "This is most likely in error; please read the manual page for details.\n"
		                "If you really want to use this command, please put the word EXPERT\n"
		                "into a line of its own in your ~/.urlview file."));

	/*** compile the regexp ***/
	regex_t rx;
	int regerr = regcomp(&rx, regexp ?: DEFAULT_REGEXP, REG_EXTENDED | REG_ICASE | REG_NEWLINE);
	if(regerr)
		errx(1, "%s: %s", regexp ?: DEFAULT_REGEXP, regex_error(&rx, regerr));
	free(regexp);

	/*** prepare arguments ***/
	off_t startline = 0;
	bool reopen_tty = false;
	size_t current = 0, oldcurrent = 0;

	opterr = false;
	for(int opt; (opt = getopt(argc, argv, "+0::1::2::3::4::5::6::7::8::9::")) != -1;) {
		if(opt == '?') {
			--optind;
			break;
		}


		if(optarg) {
			char * end;
			errno     = 0;
			startline = strtoll(optarg - 1, &end, 10);
			if(errno || *end) {
				errno = errno ? errno : EINVAL;
				err(1, "-%s", optarg - 1);
			}
		} else
			startline = opt - '0';
		current = (size_t)-1;
	}
	if(optind == argc)
		argv[--optind] = "-";

	/*** find matching patterns ***/
	struct url * url = NULL;
	size_t urlsize   = 0;
	size_t urlcount  = 0;
	bool error       = false;
	for(int i = optind; i < argc; ++i) {
		if(!strcmp("-", argv[i])) {
			fp         = stdin;
			reopen_tty = true;
		} else if(!(fp = fopen(argv[i], "re"))) {
			warn("%s", argv[i]);
			error = true;
			continue;
		}

		for(ssize_t linelen; (linelen = getline(&line, &linecap, fp)) != -1;) {
			--startline;
			size_t offset = 0;

			for(regmatch_t match; (match = (regmatch_t){.rm_so = 0, .rm_eo = linelen - offset}),
			                      !regexec(&rx, line + offset, 1, &match, (offset ? REG_NOTBOL : 0) | REG_STARTEND_OPT);) {
				size_t len = match.rm_eo - match.rm_so;
				if(urlcount >= urlsize) {
					size_t urlsizetmp = urlsize ? urlsize * 2 : 16;
					void * urltmp     = reallocarray(url, urlsizetmp, sizeof(*url));
					if(urltmp == NULL) {
					cantalloc:
						warn(gettext("couldn't allocate memory for additional URLs, only first %zu displayed"), urlsize);
						goto got_urls;
					} else {
						urlsize = urlsizetmp;
						url     = urltmp;
					}
				}
				if(!(url[urlcount].url = malloc(len + 1)))
					goto cantalloc;
				memcpy(url[urlcount].url, line + match.rm_so + offset, len);
				url[urlcount].url[len] = 0;
				url[urlcount].urllen   = len;

				for(size_t i = 0; i < urlcount; ++i)
					if(url[i].urllen == len && !strncasecmp(url[i].url, url[urlcount].url, len)) {
						--urlcount;
						break;
					}

				if(current == (size_t)-1 && startline <= 0)
					current = urlcount;
				++urlcount;
				offset += match.rm_eo;
			}
		}
	got_urls:
		if(fp != stdin)
			fclose(fp);
	}
	regfree(&rx);
	free(line);

	if(getenv("URLVIEW_DEBUG") || !isatty(1)) {
		for(size_t i = 0; i < urlcount; ++i)
			fwrite(url[i].url, 1, url[i].urllen, stdout), putchar('\n');
		return 0;
	}
	if(!urlcount) {
		puts(gettext("No URLs found."));
		return 1;
	}

	if(current == (size_t)-1)
		current = urlcount - 1;

	if(reopen_tty)
		if(!freopen("/dev/tty", "r", stdin))
			err(1, "/dev/tty");
	initscr();

	cbreak();
	noecho();
	curs_set(1);
	keypad(stdscr, TRUE);
	if(mouse) {
// OpenBSD shim: it ships with NCURSES_MOUSE_VERSION being 1, which excludes BUTTON[45]_PRESSED: https://builds.sr.ht/~nabijaczleweli/job/1064539
#ifndef BUTTON5_PRESSED
#define BUTTON5_PRESSED 0
#endif
#ifndef BUTTON4_PRESSED
#define BUTTON4_PRESSED 0
#endif
		mousemask(BUTTON1_CLICKED | BUTTON3_CLICKED | BUTTON5_PRESSED | BUTTON4_PRESSED, NULL);
		mouseinterval(5);
	}

//                                      title line
#define urlswin_logical_height (LINES - 1 - 1)
	//                                        status line
	WINDOW * urlswin = newpad(LINES, COLS);
	if(!urlswin)
		return endwin(), 1;

	enum redraw redraw         = FULL;
	struct enter_string search = {};
	regex_t search_rx          = {.re_nsub = (size_t)-1};
	int page_of_current        = 0;
	size_t first_on_page       = 0;
	int fudge                  = 0;
	for(bool done = false; !done;) {
		switch(redraw) {
			case FULL: {
				wresize(urlswin, LINES, COLS);

				/* "N URLs" is on top of "Press q to quit" is on top of the branding
				 * "N URLs" is left margin, "Press q to quit" is right margin, branding goes to center of remaining
				 * This unfortunately means we have to draw "N URLs" and "Press q to quit" first to a scratch window to establish the width,
				 * (urlswin is good since it's cleared below anyway; this approach is recommended by Dickey: https://stackoverflow.com/a/70590135/2851815),
				 * then draw them in the right order to stdscr.
				 */
				clear();
				standout();

				mvwprintw(urlswin, 0, 0, ngettext("%zu URL", "%zu URLs", urlcount), urlcount);
				int urlswidth = getcurx(urlswin);

				cc_t intr = CINTR;
				struct termios termios;
				if(!tcgetattr(0, &termios))
					intr = termios.c_cc[VINTR];
				char intr_s[4] = {};  // M-^?
				if(intr != _POSIX_VDISABLE) {
					char * intr_cur = intr_s;
					if(intr & 0x80)
						*intr_cur++ = 'M', *intr_cur++ = '-';
					intr &= 0x7F;
					if(isprint(intr))
						*intr_cur++ = intr;
					else if(intr == 0x7F)
						*intr_cur++ = '^', *intr_cur++ = '?';
					else
						*intr_cur++ = '^', *intr_cur++ = intr + '@';
					mvwprintw(urlswin, 0, 0, gettext("Press q or %.*s to quit!"), (int)sizeof(intr_s), intr_s);
				} else
					mvwaddstr(urlswin, 0, 0, gettext("Press q to quit!"));

#define BRAND "urlview-ng " VERSION ""
				mvwaddstr(stdscr, 0, urlswidth + (COLS - getcurx(urlswin) - urlswidth) / 2 - (sizeof(BRAND) - 1) / 2, BRAND);
				if(intr != _POSIX_VDISABLE)
					mvwprintw(stdscr, 0, COLS - getcurx(urlswin), gettext("Press q or %.*s to quit!"), (int)sizeof(intr_s), intr_s);
				else
					mvwaddstr(stdscr, 0, COLS - getcurx(urlswin), gettext("Press q to quit!"));

				mvwprintw(stdscr, 0, 0, ngettext("%zu URL", "%zu URLs", urlcount), urlcount);

				standend();
				wnoutrefresh(stdscr);
			}
				__attribute__((fallthrough));
			case INDEX:
				wclear(urlswin);
				wmove(urlswin, 0, 0);
				for(size_t i = 0; i < urlcount; ++i) {
#define EXPAND()                                  \
	{                                               \
		int sizey, sizex;                             \
		getmaxyx(urlswin, sizey, sizex);              \
		if(wresize(urlswin, sizey * 2, sizex) == ERR) \
			break;                                      \
	}
#define EXPANDONSCROLL(...)         \
	if(__VA_ARGS__ != OK) {           \
		wmove(urlswin, starty, startx); \
		EXPAND();                       \
		goto again;                     \
	}
					int starty, startx;
					getyx(urlswin, starty, startx);

				again:
					EXPANDONSCROLL(waddstr(urlswin, "   "));
					getyx(urlswin, url[i].cursor_y, url[i].cursor_x);
					--url[i].cursor_x;
					EXPANDONSCROLL(wprintw(urlswin, "%4zu", i + 1));
					EXPANDONSCROLL(waddch(urlswin, ' '));
					EXPANDONSCROLL(waddnstr(urlswin, url[i].url, url[i].urllen));
					url[i].last_y = getcury(urlswin);

					if(i != urlcount - 1)
						if(waddch(urlswin, '\n') != OK) {
							EXPAND();
							waddch(urlswin, '\n');
						}
				}
				__attribute__((fallthrough));
			case MOTION:
				mvwaddstr(urlswin, url[oldcurrent].cursor_y, url[oldcurrent].cursor_x - 2, "  ");
				wstandout(urlswin);
				mvwaddstr(urlswin, url[current].cursor_y, url[current].cursor_x - 2, "->");
				wstandend(urlswin);

				page_of_current = url[current].cursor_y / urlswin_logical_height;
				first_on_page   = 0;
				while(url[first_on_page].cursor_y / urlswin_logical_height != page_of_current)
					++first_on_page;
				fudge = 0;  // try to get the last-URL-on-the-page to be included when it's selected
				if(url[current].last_y - url[first_on_page].cursor_y > urlswin_logical_height)
					// unclear why +1 needed here; this means we overscroll (sometimes)
					// compare the first screen on a rows 54; cols 172; teletype of
					//   ./urlview text.uv <(for i in A B C D E F H I J K L M; do tr Q $i < text.uv; done)
					// and
					//   ./urlview text.uv <(for i in A B C D E F H I J K L M; do tr Q $i < text.uv; done | fold -w 300)
					// the last link on the first screen appear to have a completely identical last_y, but the former is taller by a line?
					fudge = (url[current].last_y - url[first_on_page].cursor_y) - urlswin_logical_height + 1;
				pnoutrefresh(urlswin, /**/ url[first_on_page].cursor_y + fudge, 0, /**/ 1 /*title line*/, 0, urlswin_logical_height, COLS);
				doupdate();

				oldcurrent = current;
				__attribute__((fallthrough));
			case CURSORPOS:
				// same projection as pnoutrefresh() above
				move(url[current].cursor_y - (url[first_on_page].cursor_y + fudge) + 1 /*title line*/, url[current].cursor_x - 0 + 0);
				__attribute__((fallthrough));
			case NO:
				break;
		}
		redraw = NO;

		errno = 0;
		int c = getch();
	rekey:
		switch(c) {
			case KEY_RESIZE:
				redraw = FULL;
				break;
			case KEY_MOUSE: {
				MEVENT ev;
				getmouse(&ev);

				if(ev.bstate & ((BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON1_TRIPLE_CLICKED) |  //
				                (BUTTON3_CLICKED | BUTTON3_DOUBLE_CLICKED | BUTTON3_TRIPLE_CLICKED))) {
					if(ev.y >= LINES - 1 || !wmouse_trafo(urlswin, &ev.y, &ev.x, false))
						break;
					ev.y += url[first_on_page].cursor_y + fudge;

					for(size_t hit = first_on_page; hit != urlcount; ++hit)
						if(ev.y >= url[hit].cursor_y && ev.y <= url[hit].last_y) {
							current = hit;
							redraw  = MOTION;

							ungetch((ev.bstate & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON1_TRIPLE_CLICKED)) ? '\n' : 'y');
							break;
						}
				} else if(ev.bstate & BUTTON5_PRESSED) {
					c = KEY_DOWN;
					goto rekey;
				} else if(ev.bstate & BUTTON4_PRESSED) {
					c = KEY_UP;
					goto rekey;
				}
			} break;
			case ERR:
				if(errno == EINTR)
					continue;
				else if(errno)
					err(1, "getch()");
				__attribute__((fallthrough));
			case 'q':
			case 'x':
			case 'h':
				done = true;
				break;
			case KEY_DOWN:
			case 'j':
				if(current < urlcount - 1)
					++current;
				else {
					if(menu_wrapping)
						current = 0;
				}
				redraw = MOTION;
				break;
			case KEY_UP:
			case 'k':
				if(current)
					--current;
				else {
					if(menu_wrapping)
						current = urlcount - 1;
				}
				redraw = MOTION;
				break;
			case KEY_HOME:
			case '=':
				current = 0;
				redraw  = MOTION;
				break;
			case KEY_END:
			case '*':
			case 'G':
				current = urlcount - 1;
				redraw  = MOTION;
				break;
			case KEY_NPAGE:
			case '\006': {
				size_t first_on_next_page = first_on_page;
				while(first_on_next_page != urlcount - 1 && url[first_on_next_page].cursor_y / urlswin_logical_height != page_of_current + 1)
					++first_on_next_page;
				current = first_on_next_page;
				redraw  = MOTION;
			} break;
			case KEY_PPAGE:
			case '\002':
				if(first_on_page != 0)
					current = first_on_page - 1;
				else
					current = 0;
				redraw = MOTION;
				break;
			case '\n':
			case '\r':
			case KEY_ENTER:
			case ' ':
			case 'e':
				// edit prompt
				if(edit_url || c == 'e') {
					mvaddstr(LINES - 1, 0, gettext("URL: "));
					mmask_t oldmouse = 0;
					mousemask(0, &oldmouse);
					auto newurl = enter_string(url[current].url, url[current].urllen);
					if(newurl.len) {
						if(newurl.len != url[current].urllen || memcmp(url[current].url, newurl.data, newurl.len))
							redraw = INDEX;
						free(url[current].url);
						url[current].url    = newurl.data;
						url[current].urllen = newurl.len;
					}
					mousemask(oldmouse, NULL);
					move(LINES - 1, 0);
					clrtoeol();
					if(c == 'e' || !newurl.len)
						goto promptcancel;
				}
				endwin();


				char * execstatus    = NULL;
				size_t execstatuslen = 0;
#define EXECAPPENDONE(str, len_arg)                        \
	{                                                        \
		size_t len = (len_arg);                                \
		char * new = realloc(execstatus, execstatuslen + len); \
		if(new) {                                              \
			execstatus = new;                                    \
			memcpy(execstatus + execstatuslen, str, len);        \
			execstatuslen += len;                                \
		}                                                      \
	}
#define EXECAPPEND_PCNT_S(fmt, s, slen)                        \
	{                                                            \
		const char * pcnt = strstr(fmt, "%s");                     \
		EXECAPPENDONE(fmt, pcnt - fmt);                            \
		EXECAPPENDONE(s, slen == (size_t) - 1 ? strlen(s) : slen); \
		EXECAPPENDONE(pcnt + 2, strlen(pcnt + 2));                 \
	}

				bool okexit      = false;
				char * curcom    = command;
				size_t curcomlen = strcspn(curcom, ":");
				while(*curcom) {
					char *toexec, *tofree = NULL;
					size_t toexeclen = -1;
					if(via == ARGUMENT)
						toexec = tofree = quotesub(curcom, curcomlen, url[current].url, url[current].urllen);
					else {
						if(curcom[curcomlen])
							toexec = tofree = strndup(curcom, curcomlen);
						else
							toexec = curcom;
						toexeclen = curcomlen;
					}
					EXECAPPEND_PCNT_S(gettext("Executing: %s... "), toexec, toexeclen);
					printf(gettext("Executing: %s... "), toexec);
					fflush(stdout);
					int childret = system_via(toexec, url[current].url, via);
					free(tofree);
					if(WIFEXITED(childret) && !WEXITSTATUS(childret)) {
						EXECAPPENDONE("i", 1);
						putchar('\n');
						okexit = true;
						break;
					}

					// same format as below
					char childrets_buf[11 + 1], *childrets = childrets_buf;  // -2147483648
					size_t childrets_len = -1;
					if(WIFSIGNALED(childret))
						childrets = strsignal(WTERMSIG(childret));
					else
						childrets_len = sprintf(childrets_buf, "%d", WEXITSTATUS(childret));

					// child exit code or human-readable signal name, written after "Executing: %s... "
					EXECAPPEND_PCNT_S(gettext("%s! "), childrets, childrets_len);
					printf(gettext("%s!\n"), childrets);

					curcom += curcomlen;
					if(*curcom)
						++curcom;
					curcomlen = strcspn(curcom, ":");
				}
				if(execstatus) {
					size_t off = 0;
					for(; off != execstatuslen && mvaddnstr(LINES - 1, 0, execstatus + off, execstatuslen - off) == ERR; ++off)
						;
					if(okexit)
						mvaddch(LINES - 1, getcurx(stdscr) - 1, ACS_DIAMOND);
					free(execstatus);
				} else
					move(LINES - 1, 0);
				clrtoeol();
				redraw = MIN(redraw, CURSORPOS);
				break;
			case 'y': {
				// contents of URL, "primary"/"secondary"/"clipboard"
				mvprintw(LINES - 1, 0, gettext("Copying %.*s to %s... "), (int)url[current].urllen, url[current].url, xselection + 2);

				int pipes[2], childret;
				pipe2(pipes, O_CLOEXEC);
				pid_t xpid = vfork();
				switch(xpid) {
					case -1:  // error
						mvaddstr(LINES - 1, 0, strerror(errno));
						break;
					case 0:  // child
						dup2(pipes[0], 0);
						errno = 0;
						if(getenv("WAYLAND_DISPLAY")) {
							execlp("wl-copy", "wl-copy", strcmp(xselection, "--primary") ? NULL : "-p", (char *)NULL);
							if(errno != ENOENT)
								_exit(126);
						}
						if(getenv("DISPLAY")) {
							execlp("xclip", "xclip", "-selection", xselection + 2, (char *)NULL);
							if(errno != ENOENT)
								_exit(126);
							execlp("xsel", "xsel", "-i", xselection, (char *)NULL);
						}
						_exit(errno == ENOENT ? 127 : 126);
					default:  // parent
						close(pipes[0]);
						writev_all(pipes[1], &(struct iovec){.iov_base = url[current].url, .iov_len = url[current].urllen}, 1);
						close(pipes[1]);
						while(waitpid(xpid, &childret, 0) == -1)
							;  // EINTR
						if(!WIFEXITED(childret) || WEXITSTATUS(childret)) {
							// same format as above
							char childrets_buf[11 + 1], *childrets = childrets_buf;  // -2147483648
							if(WIFSIGNALED(childret))
								childrets = strsignal(WTERMSIG(childret));
							else
								sprintf(childrets_buf, "%d", WEXITSTATUS(childret));

							// child exit code or human-readable signal name
							printw(gettext("%s! "), childrets);
						} else
							addch(ACS_DIAMOND);
						clrtoeol();
						redraw = CURSORPOS;
						break;
				}
			} break;
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9': {
				// edit prompt
				mvaddstr(LINES - 1, 0, gettext("Jump to URL: "));
				auto num = enter_string(&(char){c}, 1);
				if(num.len) {
					static_assert(sizeof(size_t) == sizeof(unsigned long), "size mismatch");
					char * end;
					size_t i = strtoul(num.data, &end, 0);
					if(i < 1 || i > urlcount || *end) {
						// error from the above
						mvaddstr(LINES - 1, 0, gettext("No such URL!"));
						redraw = CURSORPOS;
					} else {
						current = i - 1;
						move(LINES - 1, 0);
						redraw = MOTION;
					}
					free(num.data);
					clrtoeol();
				} else
					goto promptcancel;
			} break;
			case '\f':
			case '\007':
				clearok(stdscr, TRUE);
				redraw = FULL;
				break;
			case 'n':
			case 'N':
				c = c == 'n' ? '/' : '?';
				if(search_rx.re_nsub != (size_t)-1) {
					search_common(NULL, &search_rx, urlcount, url, &redraw, &current, c == '/' ? search_forward : search_backward);
					break;
				}
				__attribute__((fallthrough));
			case '/':
			case '?':
				mvaddstr(LINES - 1, 0, c == '/' ? /* edit prompt */ gettext("Search forwards for: ") : /* edit prompt */ gettext("Search backwards for: "));
				auto newsearch = enter_string(search.data, search.len);
				if(newsearch.len) {
					free(search.data);
					search = newsearch;
					search_common(search.data, &search_rx, urlcount, url, &redraw, &current, c == '/' ? search_forward : search_backward);
				} else {
				promptcancel:
					move(LINES - 1, 0);
					clrtoeol();
					redraw = MIN(redraw, CURSORPOS);
				}
				break;
		}
	}

	endwin();
	return error;
}