about summary refs log tree commit diff stats
path: root/bollux
blob: a57e0603d4856d1e6aa5eeb4a9d0dcc68fb65bdb (plain)
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
#!/usr/bin/env bash
# bollux: a bash gemini client
# Author: Case Duckworth
# License: MIT
# Version: 0.4.0
#
# Commentary:
#
# The impetus for this program came from a Mastodon conversation I had where
# someone mentioned the "simplest possible Gemini client" was this:
#
# openssl  s_client -gin_foe -quiet -connect $server:1965 <<< "$url"
#
# That's still at the heart of this program (see `gemini_request'): `bollux' is
# basically a half-functioning convenience wrapper around that openssl call.
# The first versions of `bollux' used `gawk' and a lot of other tools on top of
# bash, but after reading Dylan Araps' Pure Bash Bible[1] and other works, I
# decided to make as much of it in Bash as possible.  Thus, currently `bollux'
# requires `bash' v. 4+, `less' (a recent, non-busybox version), `dd' for
# downloads, `openssl' for requests, and `iconv' to convert pages to UTF-8.
# Future versions will hopefully have a pager fully implemented in bash, so that
# I won't have to worry about less's weird incompatibilities and keybinding
# things.  That's a major project though, and I'm scared.
#
# The following works were referenced when writing this, and I've tried to
# credit them in comments below.  Following each link, I'll include a "short
# code" that I'll use to reference them in those comments, if necessary to keep
# them shorter than 80 characters.
#
# [1]: https://github.com/dylanaraps/pure-bash-bible [PBB]
# [2]: https://tools.ietf.org/html/rfc3986 [URLspec]
# [3]: https://gemini.circumlunar.space/docs/specification.html [GEMspec]
# [4]: https://tools.ietf.org/html/rfc1436 [GOPHERprotocol]
# [5]: https://tools.ietf.org/html/rfc4266 [GOPHERurl]
# [6]: [GOPHER_GEMINI]:
# https://github.com/jamestomasino/dotfiles-minimal/blob/master/bin/gophermap2gemini.awk
#
# Code:

# Program information
PRGN="${0##*/}"			# Easiest way to get the script name
VRSN=0.4.1			# I /try/ to follow semver?  IDK.

# Print a useful help message (`bollux -h').
bollux_usage() {
	cat <<END
$PRGN (v. $VRSN): a bash gemini client
usage:
	$PRGN [-h]
	$PRGN [-q] [-v] [URL]
flags:
	-h	show this help and exit
	-q	be quiet: log no messages
	-v	verbose: log more messages
parameters:
	URL	the URL to start in
		If not provided, the user will be prompted.
END
}

# UTILITY FUNCTIONS ############################################################

# Run a command, but log it first.
#
# See `log' for the available levels.
run() { # run COMMAND...
	# I have to add a `trap' here for SIGINT to work properly.
	trap bollux_quit SIGINT
	log debug "$*"
	"$@"
}

# Exit with an error and a message describing it.
die() { # die EXIT_CODE MESSAGE
	local ec="$1"
	shift
	log error "$*"
	exit "$ec"
}

# Exit with success, printing a fun message.
#
# The default message is from the wonderful show "Cowboy Bebop."
bollux_quit() {
	printf '\e[1m%s\e[0m:\t\e[3m%s\e[0m\n' "$PRGN" "$BOLLUX_BYEMSG"
	exit
}
# SIGINT is C-c, and I want to make sure bollux quits when it's typed.
trap bollux_quit SIGINT

# Bash built-in replacement for `sleep`
#
# PBB: #use-read-as-an-alternative-to-the-sleep-command
sleep() { # sleep SECONDS
	read -rt "$1" <> <(:) || :
}

# Trim leading and trailing whitespace from a string.
#
# PBB: #trim-leading-and-trailing-white-space-from-string
trim_string() { # trim_string STRING
	: "${1#"${1%%[![:space:]]*}"}"
	: "${_%"${_##*[![:space:]]}"}"
	printf '%s\n' "$_"
}

# Cycle a variable.
#
# e.g. 'cycle_list one,two,three' => 'two,three,one'
cycle_list() { # cycle_list LIST DELIM
	local list="${!1}" delim="$2"
	local first="${list%%${delim}*}"
	local rest="${list#*${delim}}"
	printf -v "$1" '%s%s%s' "${rest}" "${delim}" "${first}"
}

# Determine the first element of a delimited list.
#
# e.g. 'first one,two,three' => 'one'
first() { # first LIST DELIM
	local list="${!1}" delim="$2"
	printf '%s\n' "${list%%${delim}*}"
}

# Log a message to stderr (&2).
#
# TODO: document
log() { # log LEVEL MESSAGE
	[[ "$BOLLUX_LOGLEVEL" == QUIET ]] && return
	local fmt

	case "$1" in
	[dD]*) # debug
		[[ "$BOLLUX_LOGLEVEL" == DEBUG ]] || return
		fmt=34
		;;
	[eE]*) # error
		fmt=31
		;;
	*) fmt=1 ;;
	esac
	shift

	printf >&2 '\e[%sm%s:%s:\e[0m\t%s\n' "$fmt" "$PRGN" "${FUNCNAME[1]}" "$*"
}

# Set the terminal title.
set_title() { # set_title STRING
	printf '\e]2;%s\007' "$*"
}

# Prompt the user for input.
#
# This is a thin wrapper around `read', a bash built-in.  Because of the
# way bollux messes around with stein and stdout, I need to read directly from
# the TTY with this function.
prompt() { # prompt [-u] PROMPT [READ_ARGS...]
	local read_cmd=(read -e -r)
	if [[ "$1" == "-u" ]]; then
		read_cmd+=(-i "$BOLLUX_URL")
		shift
	fi
	local prompt="$1"
	shift
	read_cmd+=(-p "$prompt> ")
	"${read_cmd[@]}" </dev/tty "$@"
}

# MAIN BOLLUX DISPATCH FUNCTIONS ###############################################

# Main entry point into `bollux'.
#
# See the `if' block at the bottom of this script.
bollux() {
	run bollux_config    # TODO: figure out better config method
	run bollux_args "$@" # and argument parsing
	run bollux_init

	# If the user hasn't configured a home page, $BOLLUX_URL will be blank.
	# So, prompt the user where to go.
	if [[ ! "${BOLLUX_URL:+x}" ]]; then
		run prompt GO BOLLUX_URL
	fi
	log d "BOLLUX_URL='$BOLLUX_URL'"

	run blastoff -u "$BOLLUX_URL" # Visit the specified URL.
}

# Process command-line arguments.
bollux_args() {
	while getopts :hvq OPT; do
		case "$OPT" in
		h)
			bollux_usage
			exit
			;;
		v) BOLLUX_LOGLEVEL=DEBUG ;;
		q) BOLLUX_LOGLEVEL=QUIET ;;
		:) die 1 "Option -$OPTARG requires an argument" ;;
		*) die 1 "Unknown option: -$OPTARG" ;;
		esac
	done
	shift $((OPTIND - 1))

	# If there's a leftover argument, it's the URL to visit.
	if (($# == 1)); then
		BOLLUX_URL="$1"
	fi
}

# Source the configuration file and set remaining variables.
#
# Since `bollux_config' is loaded before `bollux_args', there's no way to
# specify a configuration file from the command line.  I run `bollux_args'
# second so that command-line options (mostly $BOLLUX_URL) can supersede
# config-file options, and I'm not sure how to rectify the situation.
#
# Anyway, the config file `bollux.conf' is just a bash file that's sourced in
# this function.  After that, I use a little bash trick to set all the remaining
# variables to default values with `: "${VAR:=value}"'.
bollux_config() {
	: "${BOLLUX_CONF_DIR:=${XDG_CONFIG_HOME:-$HOME/.config}/bollux}"
	: "${BOLLUX_CONFIG:=$BOLLUX_CONF_DIR/bollux.conf}"

	if [ -f "$BOLLUX_CONFIG" ]; then
		log debug "Loading config file '$BOLLUX_CONFIG'"
		# shellcheck disable=1090
		. "$BOLLUX_CONFIG"
	else
		log debug "Can't load config file '$BOLLUX_CONFIG'."
	fi

	## behavior
	: "${BOLLUX_TIMEOUT:=30}"                      # connection timeout
	: "${BOLLUX_MAXREDIR:=5}"                      # max redirects
	: "${BOLLUX_PORT:=1965}"                       # port number
	: "${BOLLUX_PROTO:=gemini}"                    # default protocol
	: "${BOLLUX_URL:=}"                            # start url
	: "${BOLLUX_BYEMSG:=See You Space Cowboy ...}" # bye message
	## lesskeys
	: "${KEY_OPEN:=o}"	# prompt for a link to open
	: "${KEY_GOTO:=g}"	# prompt for a page to 'goto'
	: "${KEY_GOTO_FROM:=G}"	# goto a page with current prefilled
	: "${KEY_BACK:='['}"	# go back in the history
	: "${KEY_FORWARD:=']'}" # go forward in the history
	: "${KEY_REFRESH:=r}"	# refresh the page
	: "${KEY_CYCLE_PRE:=p}" # cycle T_PRE_DISPLAY
	: "${BOLLUX_CUSTOM_LESSKEY:=$BOLLUX_CONF_DIR/bollux.lesskey}"
	## files
	: "${BOLLUX_DATADIR:=${XDG_DATA_HOME:-$HOME/.local/share}/bollux}"
	: "${BOLLUX_DOWNDIR:=.}"                       # where to save downloads
	: "${BOLLUX_LESSKEY:=$BOLLUX_DATADIR/lesskey}" # where to store binds
	: "${BOLLUX_PAGESRC:=$BOLLUX_DATADIR/pagesrc}" # where to save source
	BOLLUX_HISTFILE="$BOLLUX_DATADIR/history"      # where to save history
	## typesetting
	: "${T_MARGIN:=4}"                 # left and right margin
	: "${T_WIDTH:=0}"                  # width of the view port
					   # 0 = get term width
	: "${T_PRE_DISPLAY:=both,pre,alt}" # how to view PRE blocks
	# colors -- these will be wrapped in \e[ __ m
	C_RESET='\e[0m'         # reset
	: "${C_SIGIL:=35}"      # sigil (=>, #, ##, ###, *, ```)
	: "${C_LINK_NUMBER:=1}" # link number
	: "${C_LINK_TITLE:=4}"  # link title
	: "${C_LINK_URL:=36}"   # link URL
	: "${C_HEADER1:=1;4}"   # header 1 formatting
	: "${C_HEADER2:=1}"     # header 2 formatting
	: "${C_HEADER3:=3}"     # header 3 formatting
	: "${C_LIST:=0}"        # list formatting
	: "${C_QUOTE:=3}"       # quote formatting
	: "${C_PRE:=0}"         # preformatted text formatting
	## state
	UC_BLANK=':?:'		# internal use only, should be non-URL chars
}


# Load a URL.
#
# I was feeling fancy when I named this function -- a more descriptive name
# would be 'bollux_goto' or something.
blastoff() { # blastoff [-u] URL
	local u

	# `blastoff' assumes a "well-formed" URL by default -- i.e., a URL with
	# a protocol string and no extraneous whitespace.  Since bollux can't
	# trust the user to input a proper URL at a prompt, nor capsule authors
	# to fully-form their URLs, so the -u flag is necessary for those
	# use-cases.  Otherwise, bollux knows the URL is well-formed -- or
	# should be, due to the Gemini specification.
	if [[ "$1" == "-u" ]]; then
		u="$(run uwellform "$2")"
	else
		u="$1"
	fi

	# After ensuring the URL is well-formed, `blastoff' needs to transform
	# it according to the transform rules of RFC 3986 (see ยง5.2.2), which
	# turns relative references into absolute references that bollux can use
	# in its request to the server.  That's followed by a check that the
	# protocol is set, defaulting to Gemini if it isn't.
	#
	# Implementation detail: because Bash is really stupid when it comes to
	# arrays, the URL functions u* (see below) work with an array defined
	# with `local -a' and passed by name, not by value.  Thus, the
	# `urltransform url ...' instead of `urltransform "${url[@]}"' or
	# similar.  In addition, the `ucdef' and `ucset' functions take the name
	# of the array element as parameters, not the element itself.
	local -a url
	run utransform url "$BOLLUX_URL" "$u"
	if ! ucdef url[1]; then
		run ucset url[1] "$BOLLUX_PROTO"
	fi

	# To try and keep `bollux' as extensible as possible, I've written it
	# only to expect two functions for every protocol it supports:
	# `x_request' and `x_response', where `x' is the name of the protocol
	# (the first element of the built `url' array).  `declare -F' looks only
	# for functions in the current scope, failing if it doesn't exist.
	#
	# In between `x_request' and `x_response', `blastoff' normalizes the
	# line endings to UNIX-style (LF) for ease of display.
	{
		if declare -F "${url[1]}_request" >/dev/null 2>&1; then
			run "${url[1]}_request" "$url"
		else
			die 99 "No request handler for '${url[1]}'"
		fi
	} | run normalize | {
		if declare -F "${url[1]}_response" >/dev/null 2>&1; then
			run "${url[1]}_response" "$url"
		else
			log d \
				"No response handler for '${url[1]}';" \
				" passing thru"
			passthru
		fi
	}
}

# URLS: https://tools.ietf.org/html/rfc3986 ####################################
#
# Most of these functions are Bash implementations of functionality laid out in
# the linked RFC specification.  I'll refer to the section numbers above each
# function.
#
# In addition, most of these functions take arrays or array elements passed /by
# name/, instead of /value/ -- i.e., instead of calling `usplit $url', call
# `usplit url'.  Passing values by name is necessary because of Bash's weird
# array handling.
#
################################################################################

# Make sure a URL is "well-formed:" add a default protocol if it's missing and
# trim whitespace.
#
# Useful for URLs that were probably input by humans.
uwellform() {
	local u="$1"

	if [[ "$u" != *://* ]]; then
		u="$BOLLUX_PROTO://$u"
	fi

	u="$(trim_string "$u")"

	printf '%s\n' "$u"
}

# Split a URL into its constituent parts, placing them all in the given array.
#
# The regular expression given at the top of the function ($re) is taken
# directly from RFC 3986, Appendix B -- and if the URL provided doesn't match
# it, the function bails.
#
# `usplit' takes advantage of bash's regex abilities: when the regex comparison
# operator `=~' is used, bash populates the array $BASH_REMATCH with the groups
# matched, and ${BASH_REMATCH[0]} is the entirety of the match.  So `usplit'
# takes the matched URL, splits it using the regex, then assigns each part to an
# element of the url array NAME by using `printf -v', which prints to a
# variable.
usplit() { # usplit NAME:ARRAY URL:STRING
	local re='^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?'
	[[ $2 =~ $re ]] || return $?

	# ShellCheck doesn't see that I'm using these variables in the `for'
	# loop below, because I'm not technically using them /as/ variables, but
	# as names to the variables.  The ${!c} formation in the `printf' call
	# below performs a reverse lookup on the name to get the actual data.
	# shellcheck disable=2034
	local url="${BASH_REMATCH[0]}" \
	      scheme="${BASH_REMATCH[2]}" \
	      authority="${BASH_REMATCH[4]}" \
	      path="${BASH_REMATCH[5]}" \
	      query="${BASH_REMATCH[7]}" \
	      fragment="${BASH_REMATCH[9]}"

	# 0=url 1=scheme 2=authority 3=path 4=query 5=fragment
	local i=1 c
	for c in scheme authority path query fragment; do
		if [[ "${!c}" || "$c" == path ]]; then
			printf -v "$1[$i]" '%s' "${!c}"
		else
			printf -v "$1[$i]" '%s' "$UC_BLANK"
		fi
		((i += 1))
	done
	printf -v "$1[0]" '%s' "$url"
}

ujoin() { # ujoin NAME:ARRAY
	local -n U="$1"

	if ucdef U[1]; then
		printf -v U[0] "%s:" "${U[1]}"
	fi

	if ucdef U[2]; then
		printf -v U[0] "${U[0]}//%s" "${U[2]}"
	fi

	printf -v U[0] "${U[0]}%s" "${U[3]}"

	if ucdef U[4]; then
		printf -v U[0] "${U[0]}?%s" "${U[4]}"
	fi

	if ucdef U[5]; then
		printf -v U[0] "${U[0]}#%s" "${U[5]}"
	fi

	log d "${U[0]}"
}

ucdef() { [[ "${!1}" != "$UC_BLANK" ]]; } # ucdef NAME
ucblank() { [[ -z "${!1}" ]]; }           # ucblank NAME
ucset() {                                 # ucset NAME VALUE
	run eval "${1}='$2'"
	run ujoin "${1/\[*\]/}"
}

utransform() {   # utransform TARGET:ARRAY BASE:STRING REFERENCE:STRING
	local -a B R    # base, reference
	local -n T="$1" # target
	usplit B "$2"
	usplit R "$3"

	# initialize T
	for ((i = 1; i <= 5; i++)); do
		T[$i]="$UC_BLANK"
	done

	# 0=url 1=scheme 2=authority 3=path 4=query 5=fragment
	if ucdef R[1]; then
		T[1]="${R[1]}"
		if ucdef R[2]; then
			T[2]="${R[2]}"
		fi
		if ucdef R[3]; then
			T[3]="$(pundot "${R[3]}")"
		fi
		if ucdef R[4]; then
			T[4]="${R[4]}"
		fi
	else
		if ucdef R[2]; then
			T[2]="${R[2]}"
			if ucdef R[2]; then
				T[3]="$(pundot "${R[3]}")"
			fi
			if ucdef R[4]; then
				T[4]="${R[4]}"
			fi
		else
			if ucblank R[3]; then
				T[3]="${B[3]}"
				if ucdef R[4]; then
					T[4]="${R[4]}"
				else
					T[4]="${B[4]}"
				fi
			else
				if [[ "${R[3]}" == /* ]]; then
					T[3]="$(pundot "${R[3]}")"
				else
					T[3]="$(pmerge B R)"
					T[3]="$(pundot "${T[3]}")"
				fi
				if ucdef R[4]; then
					T[4]="${R[4]}"
				fi
			fi
			T[2]="${B[2]}"
		fi
		T[1]="${B[1]}"
	fi
	if ucdef R[5]; then
		T[5]="${R[5]}"
	fi

	ujoin T
}

pundot() { # pundot PATH:STRING
	local input="$1"
	local output
	while [[ "$input" ]]; do
		if [[ "$input" =~ ^\.\.?/ ]]; then
			input="${input#${BASH_REMATCH[0]}}"
		elif [[ "$input" =~ ^/\.(/|$) ]]; then
			input="/${input#${BASH_REMATCH[0]}}"
		elif [[ "$input" =~ ^/\.\.(/|$) ]]; then
			input="/${input#${BASH_REMATCH[0]}}"
			[[ "$output" =~ /?[^/]+$ ]]
			output="${output%${BASH_REMATCH[0]}}"
		elif [[ "$input" == . || "$input" == .. ]]; then
			input=
		else
			[[ $input =~ ^(/?[^/]*)(/?.*)$ ]] || return 1
			output="$output${BASH_REMATCH[1]}"
			input="${BASH_REMATCH[2]}"
		fi
	done
	printf '%s\n' "${output//\/\//\//}"
}

pmerge() {
	local -n b="$1"
	local -n r="$2"

	if ucblank r[3]; then
		printf '%s\n' "${b[3]//\/\//\//}"
		return
	fi

	if ucdef b[2] && ucblank b[3]; then
		printf '/%s\n' "${r[3]//\/\//\//}"
	else
		local bp=""
		if [[ "${b[3]}" == */* ]]; then
			bp="${b[3]%/*}"
		fi
		printf '%s/%s\n' "${bp%/}" "${r[3]#/}"
	fi
}

# PBB
uencode() { # uencode URL:STRING
	local LC_ALL=C
	for ((i = 0; i < ${#1}; i++)); do
		: "${1:i:1}"
		case "$_" in
		[a-zA-Z0-9.~_-])
			printf '%s' "$_"
			;;
		*)
			printf '%%%02X' "'$_"
			;;
		esac
	done
	printf '\n'
}

# PBB
udecode() { # udecode URL:STRING
	: "${1//+/ }"
	printf '%b\n' "${_//%/\\x}"
}

# GEMINI
# https://gemini.circumlunar.space/docs/specification.html
gemini_request() { # gemini_request URL
	local -a url
	usplit url "$1"

	# get rid of userinfo
	ucset url[2] "${url[2]#*@}"

	local port
	if [[ "${url[2]}" == *:* ]]; then
		port="${url[2]#*:}"
		ucset url[2] "${url[2]%:*}"
	else
		port=1965 # TODO variablize
	fi

	local ssl_cmd=(
		openssl s_client
		-crlf -quiet -connect "${url[2]}:$port"
		-servername "${url[2]}"      # SNI
		-no_ssl3 -no_tls1 -no_tls1_1 # disable old TLS/SSL versions
	)

	run "${ssl_cmd[@]}" <<<"$url"
}

gemini_response() { # gemini_response URL
	local url code meta
	local title
	url="$1"

	# we need a loop here so it waits for the first line
	while read -t "$BOLLUX_TIMEOUT" -r code meta ||
		{ (($? > 128)) && die 99 "Timeout."; }; do
		break
	done

	log d "[$code] $meta"

	case "$code" in
	1*) # input
		REDIRECTS=0
		BOLLUX_URL="$url"
		case "$code" in
		10) run prompt "$meta" ;;
		11) run prompt "$meta" -s ;; # password input
		esac
		run blastoff "?$(uencode "$REPLY")"
		;;
	2*) # OK
		REDIRECTS=0
		BOLLUX_URL="$url"
		# read ahead to find a title
		local pretitle
		while read -r; do
			pretitle="$pretitle$REPLY"$'\n'
			if [[ "$REPLY" =~ ^#[[:space:]]*(.*) ]]; then
				title="${BASH_REMATCH[1]}"
				break
			fi
		done
		run history_append "$url" "${title:-}"
		# read the body out and pipe it to display
		{
			printf '%s' "$pretitle"
			passthru
		} | run display "$meta" "${title:-}"
		;;
	3*) # redirect
		((REDIRECTS += 1))
		if ((REDIRECTS > BOLLUX_MAXREDIR)); then
			die $((100 + code)) "Too many redirects!"
		fi
		BOLLUX_URL="$url"
		run blastoff "$meta" # TODO: confirm redirect
		;;
	4*) # temporary error
		REDIRECTS=0
		die "$((100 + code))" "Temporary error [$code]: $meta"
		;;
	5*) # permanent error
		REDIRECTS=0
		die "$((100 + code))" "Permanent error [$code]: $meta"
		;;
	6*) # certificate error
		REDIRECTS=0
		log d "Not implemented: Client certificates"
		# TODO: recheck the speck
		die "$((100 + code))" "[$code] $meta"
		;;
	*)
		[[ -z "${code-}" ]] && die 100 "Empty response code."
		die "$((100 + code))" "Unknown response code: $code."
		;;
	esac
}

# GOPHER
# https://tools.ietf.org/html/rfc1436 protocol
# https://tools.ietf.org/html/rfc4266 url
gopher_request() { # gopher_request URL
	local url server port type path
	url="$1"
	port=70

	# RFC 4266
	[[ "$url" =~ gopher://([^/?#:]*)(:([0-9]+))?(/((.))?(/?.*))?$ ]]
	server="${BASH_REMATCH[1]}"
	port="${BASH_REMATCH[3]:-70}"
	type="${BASH_REMATCH[6]:-1}"
	path="${BASH_REMATCH[7]}"

	log d "URL='$url' SERVER='$server' TYPE='$type' PATH='$path'"

	exec 9<>"/dev/tcp/$server/$port"
	printf '%s\r\n' "$path" >&9
	passthru <&9
}

gopher_response() { # gopher_response URL
	local url pre type cur_server
	pre=false
	url="$1"
	# RFC 4266
	[[ "$url" =~ gopher://([^/?#:]*)(:([0-9]+))?(/((.))?(/?.*))?$ ]]
	cur_server="${BASH_REMATCH[1]}"
	type="${BASH_REMATCH[6]:-1}"

	run history_append "$url" "" # gopher doesn't really have titles, huh

	log d "TYPE='$type'"

	case "$type" in
	0) # text
		run display text/plain
		;;
	1) # menu
		run gopher_convert | run display text/gemini
		;;
	3) # failure
		die 203 "GOPHER: failed"
		;;
	7) # search
		if [[ "$url" =~ $'\t' ]]; then
			run gopher_convert | run display text/gemini
		else
			run prompt 'SEARCH'
			run blastoff "$url	$REPLY"
		fi
		;;
	*) # something else
		run download "$url"
		;;
	esac
}

# 'cat' but in pure bash
passthru() {
	while IFS= read -r; do
		printf '%s\n' "$REPLY"
	done
}

# convert gophermap to text/gemini (probably naive)
gopher_convert() {
	local type label path server port regex
	# [GOPHER_GEMINI]
	while IFS= read -r; do
		printf -v regex '(.)([^\t]*)(\t([^\t]*)\t([^\t]*)\t([^\t]*))?'
		if [[ "$REPLY" =~ $regex ]]; then
			type="${BASH_REMATCH[1]}"
			label="${BASH_REMATCH[2]}"
			path="${BASH_REMATCH[4]:-/}"
			server="${BASH_REMATCH[5]:-$cur_server}"
			port="${BASH_REMATCH[6]}"
		else
			log e "CAN'T PARSE LINE"
			printf '%s\n' "$REPLY"
			continue
		fi
		case "$type" in
		.) # end of file
			printf '.\n'
			break
			;;
		i) # label
			case "$label" in
			'#'* | '*'[[:space:]]*)
				if $pre; then
					printf '%s\n' '```'
					pre=false
				fi
				;;
			*)
				if ! $pre; then
					printf '%s\n' '```'
					pre=true
				fi
				;;
			esac
			printf '%s\n' "$label"
			;;
		h) # html link
			if $pre; then
				printf '%s\n' '```'
				pre=false
			fi
			printf '=> %s %s\n' "${path:4}" "$label"
			;;
		T) # telnet link
			if $pre; then
				printf '%s\n' '```'
				pre=false
			fi
			printf '=> telnet://%s:%s/%s%s %s\n' \
				"$server" "$port" "$type" "$path" "$label"
			;;
		*) # other type
			if $pre; then
				printf '%s\n' '```'
				pre=false
			fi
			printf '=> gopher://%s:%s/%s%s %s\n' \
				"$server" "$port" "$type" "$path" "$label"
			;;
		esac
	done
	if $pre; then
		printf '%s\n' '```'
	fi
	# close the connection
	exec 9<&-
	exec 9>&-
}

# display the fetched content
display() { # display METADATA [TITLE]
	local -a less_cmd
	local i mime charset
	# split header line
	local -a hdr
	IFS=';' read -ra hdr <<<"$1"
	# title is optional but nice looking
	local title
	if (($# == 2)); then
		title="$2"
	fi

	mime="$(trim_string "${hdr[0],,}")"
	for ((i = 1; i <= "${#hdr[@]}"; i++)); do
		h="${hdr[$i]}"
		case "$h" in
		*charset=*) charset="${h#*=}" ;;
		esac
	done

	[[ -z "$mime" ]] && mime="text/gemini"
	[[ -z "$charset" ]] && charset="utf-8"

	log debug "mime='$mime'; charset='$charset'"

	case "$mime" in
	text/*)
		set_title "$title${title:+ - }bollux"
		# render ANSI color escapes and don't wrap pre-formatted blocks
		less_cmd=(less -RS)
		mklesskey && less_cmd+=(-k "$BOLLUX_LESSKEY")
		local helpline="${KEY_OPEN}:open, "
		helpline+="${KEY_GOTO}/"
		helpline+="${KEY_GOTO_FROM}:goto, "
		helpline+="${KEY_BACK}:back, "
		helpline+="${KEY_FORWARD}:forward, "
		helpline+="${KEY_REFRESH}:refresh"
		less_cmd+=(
			# 'status'line
			-Pm"$(less_prompt_escape "$BOLLUX_URL") - bollux$"
			# helpline
			-P="$(less_prompt_escape "$helpline")$"
			# start with statusline
			-m
			# float content to the top
			+k
		)

		local typeset
		local submime="${mime#*/}"
		if declare -Fp "typeset_$submime" &>/dev/null; then
			typeset="typeset_$submime"
		else
			typeset="passthru"
		fi

		{
			run iconv -f "${charset^^}" -t "UTF-8" |
				run tee "$BOLLUX_PAGESRC" |
				run "$typeset" | #cat
				run "${less_cmd[@]}" && bollux_quit
		} || run handle_keypress "$?"
		;;
	*) run download "$BOLLUX_URL" ;;
	esac
}

# escape strings for the less prompt
less_prompt_escape() { # less_prompt_escape STRING
	local i
	for ((i = 0; i < ${#1}; i++)); do
		: "${1:i:1}"
		case "$_" in
		[\?:\.%\\]) printf '\%s' "$_" ;;
		*) printf '%s' "$_" ;;
		esac
	done
	printf '\n'
}

# generate a lesskey(1) file for custom keybinds
mklesskey() { # mklesskey
	if [[ -f "$BOLLUX_CUSTOM_LESSKEY" ]]; then
		log d "Using custom lesskey: '$BOLLUX_CUSTOM_LESSKEY'"
		BOLLUX_LESSKEY="${BOLLUX_CUSTOM_LESSKEY}"
	elif [[ -f "$BOLLUX_LESSKEY" ]]; then
		log d "Found lesskey: '$BOLLUX_LESSKEY'"
	else
		log d "Generating lesskey: '$BOLLUX_LESSKEY'"
		lesskey -o "$BOLLUX_LESSKEY" - <<END
#command
${KEY_OPEN} quit 0 # 48 open a link
${KEY_GOTO} quit 1 # 49 goto a url
${KEY_BACK} quit 2 # 50 back
${KEY_FORWARD} quit 3 # 51 forward
${KEY_REFRESH} quit 4 # 52 re-request / download
${KEY_GOTO_FROM} quit 5 # 53 goto a url (pre-filled)
${KEY_CYCLE_PRE} quit 6 # 54 cycle T_PRE_DISPLAY and refresh
# other keybinds
\\40 forw-screen-force
h left-scroll
l right-scroll
? status   # 'status' will show a little help thing.
= noaction
END
	fi
}

# normalize files
normalize() {
	shopt -s extglob
	while IFS= read -r; do
		# normalize line endings
		printf '%s\n' "${REPLY//$'\r'?($'\n')/}"
	done
	shopt -u extglob
}

# typeset a text/gemini document
typeset_gemini() {
	local pre=false
	local ln=0 # link number

	if ((T_WIDTH == 0)); then
		shopt -s checkwinsize
		(
			:
			:
		) # dumb formatting brought to you by shfmt
		log d "LINES=$LINES; COLUMNS=$COLUMNS"
		T_WIDTH=$COLUMNS
	fi
	WIDTH=$((T_WIDTH - T_MARGIN))
	((WIDTH < 0)) && WIDTH=80  # default if dumb
	S_MARGIN=$((T_MARGIN - 1)) # spacing

	log d "T_WIDTH=$T_WIDTH"
	log d "WIDTH=$WIDTH"
	log d "$T_PRE_DISPLAY"

	while IFS= read -r; do
		case "$REPLY" in
		'```'*)
			PRE_LINE_FORCE=false
			if $pre; then
				pre=false
			else
				pre=true
			fi
			case "${T_PRE_DISPLAY%%,*}" in
			pre)
				:
				;;
			alt | both)
				$pre && PRE_LINE_FORCE=true \
					gemini_pre "${REPLY#\`\`\`}"
				;;
			esac
			continue
			;;
		'=>'*)
			: $((ln += 1))
			gemini_link "$REPLY" $pre "$ln"
			;;
		'#'*) gemini_header "$REPLY" $pre ;;
		'*'[[:space:]]*)
			gemini_list "$REPLY" $pre
			;;
		'>'*)
			gemini_quote "$REPLY" $pre
			;;
		*) gemini_text "$REPLY" $pre ;;
		esac
	done
}

gemini_link() {
	local re="^(=>)[[:blank:]]*([^[:blank:]]+)[[:blank:]]*(.*)"
	local s t a # sigil, text, annotation(url)
	local ln="$3"
	if ! ${2-false} && [[ "$1" =~ $re ]]; then
		s="${BASH_REMATCH[1]}"
		a="${BASH_REMATCH[2]}"
		t="${BASH_REMATCH[3]}"
		if [[ -z "$t" ]]; then
			t="$a"
			a=
		fi

		printf "\e[${C_SIGIL}m%${S_MARGIN}s ${C_RESET}" "$s"
		printf "\e[${C_LINK_NUMBER}m[%d]${C_RESET} " "$ln"
		fold_line -n -B "\e[${C_LINK_TITLE}m" -A "${C_RESET}" \
			-l "$((${#ln} + 3))" -m "${T_MARGIN}" \
			"$WIDTH" "$(trim_string "$t")"
		fold_line -B " \e[${C_LINK_URL}m" \
			-A "${C_RESET}" \
			-l "$((${#ln} + 3 + ${#t}))" \
			-m "$((T_MARGIN + ${#ln} + 2))" \
			"$WIDTH" "$a"
	else
		gemini_pre "$1"
	fi
}

gemini_header() {
	local re="^(#+)[[:blank:]]*(.*)"
	local s t a # sigil, text, annotation(lvl)
	if ! ${2-false} && [[ "$1" =~ $re ]]; then
		s="${BASH_REMATCH[1]}"
		a="${#BASH_REMATCH[1]}"
		t="${BASH_REMATCH[2]}"
		local hdrfmt
		hdrfmt="$(eval echo "\$C_HEADER$a")"

		printf "\e[${C_SIGIL}m%${S_MARGIN}s ${C_RESET}" "$s"
		fold_line -B "\e[${hdrfmt}m" -A "${C_RESET}" -m "${T_MARGIN}" \
			"$WIDTH" "$t"
	else
		gemini_pre "$1"
	fi
}

gemini_list() {
	local re="^(\*)[[:blank:]]*(.*)"
	local s t # sigil, text
	if ! ${2-false} && [[ "$1" =~ $re ]]; then
		s="${BASH_REMATCH[1]}"
		t="${BASH_REMATCH[2]}"

		printf "\e[${C_SIGIL}m%${S_MARGIN}s ${C_RESET}" "$s"
		fold_line -B "\e[${C_LIST}m" -A "${C_RESET}" -m "$T_MARGIN" \
			"$WIDTH" "$t"
	else
		gemini_pre "$1"
	fi
}

gemini_quote() {
	local re="^(>)[[:blank:]]*(.*)"
	local s t # sigil, text
	if ! ${2-false} && [[ "$1" =~ $re ]]; then
		s="${BASH_REMATCH[1]}"
		t="${BASH_REMATCH[2]}"

		printf "\e[${C_SIGIL}m%${S_MARGIN}s ${C_RESET}" "$s"
		fold_line -B "\e[${C_QUOTE}m" -A "${C_RESET}" -m "$T_MARGIN" \
			"$WIDTH" "$t"
	else
		gemini_pre "$1"
	fi
}

gemini_text() {
	if ! ${2-false}; then
		printf "%${S_MARGIN}s " ' '
		fold_line -m "$T_MARGIN" \
			"$WIDTH" "$1"
	else
		gemini_pre "$1"
	fi
}

gemini_pre() {
	# Print preformatted text, dependent on $T_PRE_DISPLAY and
	# $PRE_LINE_FORCE
	if [[ alt != "${T_PRE_DISPLAY%%,*}" ]] || $PRE_LINE_FORCE; then
		printf "\e[${C_SIGIL}m%${S_MARGIN}s " '```'
		printf "\e[${C_PRE}m%s${C_RESET}\n" "$1"
	fi
}

# wrap lines on words to WIDTH
fold_line() { # fold_line [OPTIONS...] WIDTH TEXT
	# see getopts, below, for options
	local newline=true
	local -i margin_all=0 margin_first=0 width ll=0 wl=0 wn=0
	local before="" after=""
	OPTIND=0
	while getopts nm:f:l:B:A: OPT; do
		case "$OPT" in
		n) # -n = no trailing newline
			newline=false
			;;
		m) # -m MARGIN = margin for all lines
			margin_all="$OPTARG"
			;;
		f) # -f MARGIN = margin for first line
			margin_first="$OPTARG"
			;;
		l) # -l LENGTH = length of line before starting fold
			ll="$OPTARG"
			;;
		B) # -B BEFORE = text to insert before each line
			before="$OPTARG"
			;;
		A) # -A AFTER = text to insert after each line
			after="$OPTARG"
			;;
		*) return 1 ;;
		esac
	done
	shift "$((OPTIND - 1))"
	width="$1"
	ll=$((ll % width))
	#shellcheck disable=2086
	set -- $2

	local plain=""
	if ((margin_first > 0 && ll == 0)); then
		printf "%${margin_first}s" " "
	fi
	if [[ -n "$before" ]]; then
		printf '%b' "$before"
	fi
	for word; do
		((wn += 1))
		shopt -s extglob
		plain="${word//$'\x1b'\[*([0-9;])m/}"
		shopt -u extglob
		wl=$((${#plain} + 1))
		if (((ll + wl) >= width)); then
			printf "${after:-}\n%${margin_all}s${before:-}" ' '
			ll=$wl
		else
			((ll += wl))
		fi
		printf '%s' "$word"
		((wn != $#)) && printf ' '
	done
	[[ -n "$after" ]] && printf '%b' "$after"
	$newline && printf '\n'
}

# use the exit code from less (see mklesskey) to do things
handle_keypress() { # handle_keypress CODE
	case "$1" in
	48) # o - open a link -- show a menu of links on the page
		run select_url "$BOLLUX_PAGESRC"
		;;
	49) # g - goto a url -- input a new url
		prompt GO
		run blastoff -u "$REPLY"
		;;
	50) # [ - back in the history
		run history_back || {
			sleep 0.5
			run blastoff "$BOLLUX_URL"
		}
		;;
	51) # ] - forward in the history
		run history_forward || {
			sleep 0.5
			run blastoff "$BOLLUX_URL"
		}
		;;
	52) # r - re-request the current resource
		run blastoff "$BOLLUX_URL"
		;;
	53) # G - goto a url (pre-filled with current)
		run prompt -u GO
		run blastoff -u "$REPLY"
		;;
	54) # ` - change alt-text visibility and refresh
		run cycle_list T_PRE_DISPLAY ,
		run blastoff "$BOLLUX_URL"
		;;
	55) # 55-57 -- still available for binding
		die "$?" "less(1) error"
		;;
	esac
}

# select a URL from a text/gemini file
select_url() { # select_url FILE
	run mapfile -t < <(extract_links <"$1")
	if ((${#MAPFILE[@]} == 0)); then
		log e "No links on this page!"
		sleep 0.5
		run blastoff "$BOLLUX_URL"
	fi
	PS3="OPEN> "
	select u in "${MAPFILE[@]}"; do
		case "$REPLY" in
		q) bollux_quit ;;
		[^0-9]*) run blastoff -u "$REPLY" && break ;;
		esac
		run blastoff "${u%%[[:space:]]*}" && break
	done </dev/tty
}

# extract the links from a text/gemini file
extract_links() {
	local url alt
	local re="^=>[[:space:]]*([^[:space:]]+)([[:space:]]+(.*))?$"
	while read -r; do
		log d "$re"
		if [[ $REPLY =~ $re ]]; then
			url="${BASH_REMATCH[1]}"
			alt="${BASH_REMATCH[3]}"

			if [[ "$alt" ]]; then
				printf '%s \e[34m(%s)\e[0m\n' "$url" "$alt"
			else
				printf '%s\n' "$url"
			fi
		fi
	done
}

# download $BOLLUX_URL
download() {
	tn="$(mktemp)"
	log x "Downloading: '$BOLLUX_URL' => '$tn'..."
	dd status=progress >"$tn"
	fn="$BOLLUX_DOWNDIR/${BOLLUX_URL##*/}"
	if [[ -f "$fn" ]]; then
		log x "Saved '$tn'."
	elif mv "$tn" "$fn"; then
		log x "Saved '$fn'."
	else
		log error "Error saving '$fn': downloaded to '$tn'."
	fi
}

# initialize bollux
bollux_init() {
	# Trap cleanup
	trap bollux_cleanup INT QUIT EXIT
	# State
	REDIRECTS=0
	set -f
	# History
	declare -a HISTORY # history is kept in an array
	HN=0               # position of history in the array
	run mkdir -p "${BOLLUX_HISTFILE%/*}"
	# Remove $BOLLUX_LESSKEY and re-generate keybindings (to catch rebinds)
	run rm -f "$BOLLUX_LESSKEY"
	mklesskey
}

# clean up on exit
bollux_cleanup() {
	# Stubbed in case of need in future
	:
}

# append a URL to history
history_append() { # history_append URL TITLE
	BOLLUX_URL="$1"
	# date/time, url, title (best guess)
	run printf '%(%FT%T)T\t%s\t%s\n' -1 "$1" "$2" >>"$BOLLUX_HISTFILE"
	HISTORY[$HN]="$BOLLUX_URL"
	((HN += 1))
}

# move back in history (session)
history_back() {
	log d "HN=$HN"
	((HN -= 2))
	if ((HN < 0)); then
		HN=0
		log e "Beginning of history."
		return 1
	fi
	run blastoff "${HISTORY[$HN]}"
}

# move forward in history (session)
history_forward() {
	log d "HN=$HN"
	if ((HN >= ${#HISTORY[@]})); then
		HN="${#HISTORY[@]}"
		log e "End of history."
		return 1
	fi
	run blastoff "${HISTORY[$HN]}"
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
	${DEBUG:-false} && set -x
	run bollux "$@"
fi