From 9bdc70b12ab3a79b226a8562a1db1293b4b1dcf4 Mon Sep 17 00:00:00 2001
From: Case Duckworth
Date: Sat, 23 May 2020 23:49:48 -0500
Subject: Update display() to use less and better mimetypes

---
 bollux | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 56 insertions(+), 10 deletions(-)

diff --git a/bollux b/bollux
index 079c83b..7711dd6 100755
--- a/bollux
+++ b/bollux
@@ -289,13 +289,29 @@ handle() { # handle URL < RESPONSE
 }
 
 # display the page
-display() { # display MIMETYPE < DOCUMENT
-	mimetype="$1"
-	case "$mimetype" in
+display() { # display META < DOCUMENT
+	case "$1" in
+	*\;*)
+		mime="$(cut -d\; -f1 <<<"$1" | trim)"
+		charset="$(cut -d\; -f2 <<<"$1" | trim)"
+		;;
+	*) mime="$(trim <<<"$1")" ;;
+	esac
+	[ -z "$mime" ] && mime="text/gemini"
+	if [ -z "$charset" ]; then
+		charset="utf-8"
+	else
+		charset="${charset#*=}"
+	fi
+
+	log 5 "mime=$mime; charset=$charset"
+
+	case "$mime" in
+	text/gemini)
+		lfn | typeset_gemini | less -R
+		;;
 	text/*)
-		# normalize line endings to "\n"
-		# gawk 'BEGIN{RS=""}{gsub(/\r\n?/,"\n");print}'
-		cat
+		lfn
 		# TODO: use less with linking and stuff
 		# less -R -p'^=>' +g
 		# lesskey:
@@ -308,12 +324,42 @@ display() { # display MIMETYPE < DOCUMENT
 		# also look into the prompt, the filename, and input preprocessor
 		# ($LESSOPEN, $LESSCLOSE)
 		;;
-	*)
-		download "$URL"
-		;;
+	*) download "$URL" ;;
 	esac
 }
 
+# normalize line endings to \n (LF)
+lfn() {
+	gawk 'BEGIN{RS="\n\n"}{gsub(/\r\n?/,"\n");print;print ""}'
+}
+
+# typeset text
+typeset_gemini() { # typeset_gemini < INPUT
+	gawk '
+	BEGIN { pre = 0 }
+	/^###/ { sub(/^#+[[:space:]]*/, ""); 
+		printf " \033[3m%s\033[0m\n", $0
+	next }
+	/^##/  { sub(/^#+[[:space:]]*/, ""); 
+		printf " \033[1m%s\033[0m\n", $0
+	next }
+	/^#/   { sub(/^#+[[:space:]]*/, ""); 
+		printf " \033[1;4m%s\033[0m\n", $0
+	next }
+	/^=>/  { 
+		sub(/=>[[:space:]]*/, "")
+		url = $1; desc = ""
+		for (w=2;w<=NF;w++) 
+			desc = desc (desc?" ":"") $w
+		printf " \033[1m[%s]\033[0m \033[4m%s\033[0m \033[36m%s\033[0m\n", 
+			(++ln), desc, "(" url ")"
+	next }
+	# /^\*/  { sub(/\*[[:space:]]*/, ""); }
+	/```/  { pre = !pre; next }
+	{ sub(/^/, " "); print }
+	'
+}
+
 download() { # download URL < FILE
 	tn="$(mktemp)"
 	dd status=progress >"$tn"
@@ -363,7 +409,7 @@ bollux_setup() {
 }
 
 bollux_cleanup() {
-	echo
+	exit $?
 }
 
 if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
-- 
cgit 1.4.1-21-gabe81