Bugfix: file name suggestion for gemini downloads.
[elpher.git] / elpher.el
1 ;;; elpher.el --- A friendly gopher client  -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2019 Tim Vaughan
4
5 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
6 ;; Created: 11 April 2019
7 ;; Version: 2.7.4
8 ;; Keywords: comm gopher
9 ;; Homepage: http://thelambdalab.xyz/elpher
10 ;; Package-Requires: ((emacs "26"))
11
12 ;; This file is not part of GNU Emacs.
13
14 ;; This program is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Elpher aims to provide a practical and friendly gopher client
30 ;; for GNU Emacs.  It supports:
31
32 ;; - intuitive keyboard and mouse-driven browsing,
33 ;; - out-of-the-box compatibility with evil-mode,
34 ;; - clickable web and gopher links *in plain text*,
35 ;; - caching of visited sites,
36 ;; - pleasant and configurable colouring of Gopher directories,
37 ;; - direct visualisation of image files,
38 ;; - a simple bookmark management system,
39 ;; - connections using TLS encryption,
40 ;; - the fledgling Gemini protocol,
41 ;; - the greybeard Finger protocol.
42
43 ;; To launch Elpher, simply use 'M-x elpher'.  This will open a start
44 ;; page containing information on key bindings and suggested starting
45 ;; points for your gopher exploration.
46
47 ;; Full instructions can be found in the Elpher info manual.
48
49 ;; Elpher is under active development.  Any suggestions for
50 ;; improvements are welcome, and can be made on the official
51 ;; project page, gopher://thelambdalab.xyz/1/projects/elpher/.
52
53 ;;; Code:
54
55 (provide 'elpher)
56
57 ;;; Dependencies
58 ;;
59
60 (require 'seq)
61 (require 'pp)
62 (require 'shr)
63 (require 'url-util)
64 (require 'subr-x)
65 (require 'dns)
66 (require 'ansi-color)
67 (require 'nsm)
68
69
70 ;;; Global constants
71 ;;
72
73 (defconst elpher-version "2.7.4"
74   "Current version of elpher.")
75
76 (defconst elpher-margin-width 6
77   "Width of left-hand margin used when rendering indicies.")
78
79 (defconst elpher-type-map
80   '(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
81     ((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
82     ((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
83     ((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
84     ((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
85     ((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
86     ((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
87     ((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
88     ((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
89     ((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
90     ((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
91     ((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
92     ((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
93     (gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
94     (finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
95     (telnet elpher-get-telnet-page nil "tel" elpher-telnet)
96     (other-url elpher-get-other-url-page nil "url" elpher-other-url)
97     ((special bookmarks) elpher-get-bookmarks-page nil "/" elpher-index)
98     ((special start) elpher-get-start-page nil))
99   "Association list from types to getters, renderers, margin codes and index faces.")
100
101
102 ;;; Customization group
103 ;;
104
105 (defgroup elpher nil
106   "A gopher client."
107   :group 'applications)
108
109 ;; General appearance and customizations
110
111 (defcustom elpher-open-urls-with-eww nil
112   "If non-nil, open URL selectors using eww.
113 Otherwise, use the system browser via the BROWSE-URL function."
114   :type '(boolean))
115
116 (defcustom elpher-use-header t
117   "If non-nil, display current page information in buffer header."
118   :type '(boolean))
119
120 (defcustom elpher-auto-disengage-TLS nil
121   "If non-nil, automatically disengage TLS following an unsuccessful connection.
122 While enabling this may seem convenient, it is also potentially dangerous as it
123 allows switching from an encrypted channel back to plain text without user input."
124   :type '(boolean))
125
126 (defcustom elpher-connection-timeout 5
127   "Specifies the number of seconds to wait for a network connection to time out."
128   :type '(integer))
129
130 (defcustom elpher-filter-ansi-from-text nil
131   "If non-nil, filter ANSI escape sequences from text.
132 The default behaviour is to use the ansi-color package to interpret these
133 sequences."
134   :type '(boolean))
135
136 (defcustom elpher-gemini-TLS-cert-checks nil
137   "If non-nil, verify gemini server TLS certs using the default security level.
138 Otherwise, certificate verification is disabled.
139
140 This defaults to off because it is standard practice for Gemini servers
141 to use self-signed certificates, meaning that most servers provide what
142 EMACS considers to be an invalid certificate."
143   :type '(boolean))
144
145 (defcustom elpher-gemini-max-fill-width 80
146   "Specify the maximum default width (in columns) of text/gemini documents.
147 The actual width used is the minimum of this value and the window width at
148 the time when the text is rendered."
149   :type '(integer))
150
151 (defcustom elpher-bookmarks-file (locate-user-emacs-file "elpher-bookmarks")
152   "Specify the name of the file where elpher bookmarks will be saved."
153   :type '(file))
154
155 ;; Face customizations
156
157 (defgroup elpher-faces nil
158   "Elpher face customizations."
159   :group 'elpher)
160
161 (defface elpher-index
162   '((t :inherit font-lock-keyword-face))
163   "Face used for directory type directory records.")
164
165 (defface elpher-text
166   '((t :inherit bold))
167   "Face used for text type directory records.")
168
169 (defface elpher-info
170   '((t :inherit default))
171   "Face used for info type directory records.")
172
173 (defface elpher-image
174   '((t :inherit font-lock-string-face))
175   "Face used for image type directory records.")
176
177 (defface elpher-search
178   '((t :inherit warning))
179   "Face used for search type directory records.")
180
181 (defface elpher-html
182   '((t :inherit font-lock-comment-face))
183   "Face used for html type directory records.")
184
185 (defface elpher-gemini
186   '((t :inherit font-lock-regexp-grouping-backslash))
187   "Face used for Gemini type directory records.")
188
189 (defface elpher-other-url
190   '((t :inherit font-lock-comment-face))
191   "Face used for other URL type links records.")
192
193 (defface elpher-telnet
194   '((t :inherit font-lock-function-name-face))
195   "Face used for telnet type directory records.")
196
197 (defface elpher-binary
198   '((t :inherit font-lock-doc-face))
199   "Face used for binary type directory records.")
200
201 (defface elpher-unknown
202   '((t :inherit error))
203   "Face used for directory records with unknown/unsupported types.")
204
205 (defface elpher-margin-key
206   '((t :inherit bold))
207   "Face used for directory margin key.")
208
209 (defface elpher-margin-brackets
210   '((t :inherit shadow))
211   "Face used for brackets around directory margin key.")
212
213 (defface elpher-gemini-heading1
214   '((t :inherit bold :height 1.8))
215   "Face used for gemini heading level 1.")
216
217 (defface elpher-gemini-heading2
218   '((t :inherit bold :height 1.5))
219   "Face used for gemini heading level 2.")
220
221 (defface elpher-gemini-heading3
222   '((t :inherit bold :height 1.2))
223   "Face used for gemini heading level 3.")
224
225 ;;; Model
226 ;;
227
228 ;; Address
229
230 ;; An elpher "address" object is either a url object or a symbol.
231 ;; Symbol addresses are "special", corresponding to pages generated
232 ;; dynamically for and by elpher.  All others represent pages which
233 ;; rely on content retrieved over the network.
234
235 (defun elpher-address-from-url (url-string)
236   "Create a ADDRESS object corresponding to the given URL-STRING."
237   (let ((data (match-data))) ; Prevent parsing clobbering match data
238     (unwind-protect
239         (let ((url (url-generic-parse-url url-string)))
240           (unless (and (not (url-fullness url)) (url-type url))
241             (setf (url-fullness url) t)
242             (setf (url-filename url)
243                   (url-unhex-string (url-filename url)))
244             (unless (url-type url)
245               (setf (url-type url) "gopher"))
246             (when (or (equal "gopher" (url-type url))
247                       (equal "gophers" (url-type url)))
248               ;; Gopher defaults
249               (unless (url-host url)
250                 (setf (url-host url) (url-filename url))
251                 (setf (url-filename url) ""))
252               (when (or (equal (url-filename url) "")
253                         (equal (url-filename url) "/"))
254                 (setf (url-filename url) "/1")))
255             (when (equal "gemini" (url-type url))
256               ;; Gemini defaults
257               (if (equal (url-filename url) "")
258                   (setf (url-filename url) "/"))))
259           url)
260       (set-match-data data))))
261
262 (defun elpher-make-gopher-address (type selector host port &optional tls)
263   "Create an ADDRESS object using gopher directory record attributes.
264 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
265 If the optional attribute TLS is non-nil, the address will be marked as
266 requiring gopher-over-TLS."
267   (cond
268    ((and (equal type ?h)
269          (string-prefix-p "URL:" selector))
270     (elpher-address-from-url (elt (split-string selector "URL:") 1)))
271    ((equal type ?8)
272     (elpher-address-from-url
273      (concat "telnet"
274              "://" host
275              ":" (number-to-string port))))
276    (t
277     (elpher-address-from-url
278      (concat "gopher" (if tls "s" "")
279              "://" host
280              ":" (number-to-string port)
281              "/" (string type)
282              selector)))))
283
284 (defun elpher-make-special-address (type)
285   "Create an ADDRESS object corresponding to the given special address symbol TYPE."
286   type)
287
288 (defun elpher-address-to-url (address)
289   "Get string representation of ADDRESS, or nil if ADDRESS is special."
290   (if (not (elpher-address-special-p address))
291       (url-encode-url (url-recreate-url address))
292     nil))
293
294 (defun elpher-address-type (address)
295   "Retrieve type of ADDRESS object.
296 This is used to determine how to retrieve and render the document the
297 address refers to, via the table `elpher-type-map'."
298   (if (symbolp address)
299       (list 'special address)
300     (let ((protocol (url-type address)))
301       (cond ((or (equal protocol "gopher")
302                  (equal protocol "gophers"))
303              (list 'gopher
304                    (if (member (url-filename address) '("" "/"))
305                        ?1
306                      (string-to-char (substring (url-filename address) 1)))))
307             ((equal protocol "gemini")
308              'gemini)
309             ((equal protocol "telnet")
310              'telnet)
311             ((equal protocol "finger")
312              'finger)
313             (t 'other-url)))))
314
315 (defun elpher-address-protocol (address)
316   "Retrieve the transport protocol for ADDRESS.  This is nil for special addresses."
317   (if (symbolp address)
318       nil
319     (url-type address)))
320
321 (defun elpher-address-filename (address)
322   "Retrieve the filename component of ADDRESS.
323 For gopher addresses this is a combination of the selector type and selector."
324   (if (symbolp address)
325       nil
326     (url-filename address)))
327
328 (defun elpher-address-host (address)
329   "Retrieve host from ADDRESS object."
330   (url-host address))
331
332 (defun elpher-address-user (address)
333   "Retrieve user from ADDRESS object."
334   (url-user address))
335
336 (defun elpher-address-port (address)
337   "Retrieve port from ADDRESS object.
338 If no address is defined, returns 0.  (This is for compatibility with the URL library.)"
339   (if (symbolp address)
340       0
341     (url-port address)))
342
343 (defun elpher-address-special-p (address)
344   "Return non-nil if ADDRESS object is special (e.g. start page, bookmarks page)."
345   (symbolp address))
346
347 (defun elpher-address-gopher-p (address)
348   "Return non-nill if ADDRESS object is a gopher address."
349   (and (not (elpher-address-special-p address))
350        (member (elpher-address-protocol address) '("gopher gophers"))))
351
352 (defun elpher-gopher-address-selector (address)
353   "Retrieve gopher selector from ADDRESS object."
354   (if (member (url-filename address) '("" "/"))
355       ""
356     (substring (url-filename address) 2)))
357
358
359 ;; Cache
360
361 (defvar elpher-content-cache (make-hash-table :test 'equal))
362 (defvar elpher-pos-cache (make-hash-table :test 'equal))
363
364 (defun elpher-get-cached-content (address)
365   "Retrieve the cached content for ADDRESS, or nil if none exists."
366   (gethash address elpher-content-cache))
367
368 (defun elpher-cache-content (address content)
369   "Set the content cache for ADDRESS to CONTENT."
370   (puthash address content elpher-content-cache))
371
372 (defun elpher-get-cached-pos (address)
373   "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
374   (gethash address elpher-pos-cache))
375
376 (defun elpher-cache-pos (address pos)
377   "Set the cursor position cache for ADDRESS to POS."
378   (puthash address pos elpher-pos-cache))
379
380
381 ;; Page
382
383 (defun elpher-make-page (display-string address)
384   "Create a page with DISPLAY-STRING and ADDRESS."
385   (list display-string address))
386
387 (defun elpher-page-display-string (page)
388   "Retrieve the display string corresponding to PAGE."
389   (elt page 0))
390
391 (defun elpher-page-address (page)
392   "Retrieve the address corresponding to PAGE."
393   (elt page 1))
394
395 (defun elpher-page-set-address (page new-address)
396   "Set the address corresponding to PAGE to NEW-ADDRESS."
397   (setcar (cdr page) new-address))
398
399 (defvar elpher-current-page nil)
400 (defvar elpher-history nil)
401
402 (defun elpher-visit-page (page &optional renderer no-history)
403   "Visit PAGE using its own renderer or RENDERER, if non-nil.
404 Additionally, push PAGE onto the stack of previously-visited pages,
405 unless NO-HISTORY is non-nil."
406   (elpher-save-pos)
407   (elpher-process-cleanup)
408   (unless (or no-history
409               (equal (elpher-page-address elpher-current-page)
410                      (elpher-page-address page)))
411     (push elpher-current-page elpher-history))
412   (setq elpher-current-page page)
413   (let* ((address (elpher-page-address page))
414          (type (elpher-address-type address))
415          (type-record (cdr (assoc type elpher-type-map))))
416     (if type-record
417         (funcall (car type-record)
418                  (if renderer
419                      renderer
420                    (cadr type-record)))
421       (elpher-visit-previous-page)
422       (pcase type
423         (`(gopher ,type-char)
424          (error "Unsupported gopher selector type '%c' for '%s'"
425                 type-char (elpher-address-to-url address)))
426         (other
427          (error "Unsupported address type '%S' for '%s'"
428                 other (elpher-address-to-url address)))))))
429
430 (defun elpher-visit-previous-page ()
431   "Visit the previous page in the history."
432   (let ((previous-page (pop elpher-history)))
433     (if previous-page
434         (elpher-visit-page previous-page nil t)
435       (error "No previous page"))))
436       
437 (defun elpher-reload-current-page ()
438   "Reload the current page, discarding any existing cached content."
439   (elpher-cache-content (elpher-page-address elpher-current-page) nil)
440   (elpher-visit-page elpher-current-page))
441
442 (defun elpher-save-pos ()
443   "Save the current position of point to the current page."
444   (when elpher-current-page
445     (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
446
447 (defun elpher-restore-pos ()
448   "Restore the position of point to that cached in the current page."
449   (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
450     (if pos
451         (goto-char pos)
452       (goto-char (point-min)))))
453
454
455 ;;; Buffer preparation
456 ;;
457
458 (defun elpher-update-header ()
459   "If `elpher-use-header' is true, display current page info in window header."
460   (if elpher-use-header
461       (let* ((display-string (elpher-page-display-string elpher-current-page))
462              (address (elpher-page-address elpher-current-page))
463              (tls-string (if (and (not (elpher-address-special-p address))
464                                   (member (elpher-address-protocol address)
465                                           '("gophers" "gemini")))
466                              " [TLS encryption]"
467                            ""))
468              (header (concat display-string
469                              (propertize tls-string 'face 'bold))))
470         (setq header-line-format header))))
471
472 (defmacro elpher-with-clean-buffer (&rest args)
473   "Evaluate ARGS with a clean *elpher* buffer as current."
474   (list 'with-current-buffer "*elpher*"
475         '(elpher-mode)
476         (append (list 'let '((inhibit-read-only t))
477                       '(setq-local network-security-level
478                                    (default-value 'network-security-level))
479                       '(erase-buffer)
480                       '(elpher-update-header))
481                 args)))
482
483
484 ;;; Text Processing
485 ;;
486
487 (defvar elpher-user-coding-system nil
488   "User-specified coding system to use for decoding text responses.")
489
490 (defun elpher-decode (string)
491   "Decode STRING using autodetected or user-specified coding system."
492   (decode-coding-string string
493                         (if elpher-user-coding-system
494                             elpher-user-coding-system
495                           (detect-coding-string string t))))
496
497 (defun elpher-preprocess-text-response (string)
498   "Preprocess text selector response contained in STRING.
499 This involes decoding the character representation, and clearing
500 away CRs and any terminating period."
501   (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
502                                            (replace-regexp-in-string "\r" "" string))))
503
504
505 ;;; Network error reporting
506 ;;
507
508 (defun elpher-network-error (address error)
509   "Display ERROR message following unsuccessful negotiation with ADDRESS.
510 ERROR can be either an error object or a string."
511   (elpher-with-clean-buffer
512    (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
513            "When attempting to retrieve " (elpher-address-to-url address) ":\n"
514            (if (stringp error) error (error-message-string error)) "\n"
515            (propertize "\n----------------\n\n" 'face 'error)
516            "Press 'u' to return to the previous page.")))
517
518
519 ;;; Gopher selector retrieval
520 ;;
521
522 (defvar elpher-network-timer nil
523   "Timer used for network connections.")
524
525 (defun elpher-process-cleanup ()
526   "Immediately shut down any extant elpher process and timers."
527   (let ((p (get-process "elpher-process")))
528     (if p (delete-process p)))
529   (if (timerp elpher-network-timer)
530       (cancel-timer elpher-network-timer)))
531
532 (defvar elpher-use-tls nil
533   "If non-nil, use TLS to communicate with gopher servers.")
534
535 (defun elpher-get-selector (address renderer &optional force-ipv4)
536   "Retrieve selector specified by ADDRESS, then render it using RENDERER.
537 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
538 to ADDRESS."
539   (when (equal (elpher-address-protocol address) "gophers")
540     (if (gnutls-available-p)
541         (when (not elpher-use-tls)
542           (setq elpher-use-tls t)
543           (message "Engaging TLS gopher mode."))
544       (error "Cannot retrieve TLS gopher selector: GnuTLS not available")))
545   (unless (< (elpher-address-port address) 65536)
546     (error "Cannot retrieve gopher selector: port number > 65536"))
547   (condition-case nil
548       (let* ((kill-buffer-query-functions nil)
549              (port (elpher-address-port address))
550              (host (elpher-address-host address))
551              (selector-string-parts nil)
552              (proc (open-network-stream "elpher-process"
553                                         nil
554                                         (if force-ipv4 (dns-query host) host)
555                                         (if (> port 0) port 70)
556                                         :type (if elpher-use-tls 'tls 'plain)
557                                         :nowait t))
558              (timer (run-at-time elpher-connection-timeout
559                                  nil
560                                  (lambda ()
561                                    (pcase (process-status proc)
562                                      ('failed
563                                       (if (and (not (equal (elpher-address-protocol address)
564                                                            "gophers"))
565                                                elpher-use-tls
566                                                (or elpher-auto-disengage-TLS
567                                                    (yes-or-no-p "Could not establish encrypted connection.  Disable TLS mode?")))
568                                           (progn
569                                             (message "Disabling TLS mode.")
570                                             (setq elpher-use-tls nil)
571                                             (elpher-get-selector address renderer))
572                                         (elpher-network-error address "Could not establish encrypted connection")))
573                                      ('connect
574                                       (elpher-process-cleanup)
575                                       (unless force-ipv4
576                                         (message "Connection timed out. Retrying with IPv4 address.")
577                                         (elpher-get-selector address renderer t))))))))
578         (setq elpher-network-timer timer)
579         (set-process-coding-system proc 'binary)
580         (set-process-filter proc
581                             (lambda (_proc string)
582                               (cancel-timer timer)
583                               (setq selector-string-parts
584                                     (cons string selector-string-parts))))
585         (set-process-sentinel proc
586                               (lambda (_proc event)
587                                 (condition-case the-error
588                                     (cond
589                                      ((string-prefix-p "deleted" event))
590                                      ((string-prefix-p "open" event)
591                                       (let ((inhibit-eol-conversion t))
592                                         (process-send-string
593                                          proc
594                                          (concat (elpher-gopher-address-selector address)
595                                                  "\r\n"))))
596                                      (t
597                                       (cancel-timer timer)
598                                       (funcall renderer (apply #'concat
599                                                                (reverse selector-string-parts)))
600                                       (elpher-restore-pos)))
601                                   (error
602                                    (elpher-network-error address the-error))))))
603     (error
604      (error "Error initiating connection to server"))))
605
606 (defun elpher-get-gopher-page (renderer)
607   "Getter function for gopher pages.
608 The RENDERER procedure is used to display the contents of the page
609 once they are retrieved from the gopher server."
610   (let* ((address (elpher-page-address elpher-current-page))
611          (content (elpher-get-cached-content address)))
612     (if (and content (funcall renderer nil))
613         (elpher-with-clean-buffer
614          (insert content)
615          (elpher-restore-pos))
616       (elpher-with-clean-buffer
617        (insert "LOADING... (use 'u' to cancel)"))
618       (condition-case the-error
619           (elpher-get-selector address renderer)
620         (error
621          (elpher-network-error address the-error))))))
622
623 ;; Index rendering
624
625 (defun elpher-insert-index (string)
626   "Insert the index corresponding to STRING into the current buffer."
627   ;; Should be able to split directly on CRLF, but some non-conformant
628   ;; LF-only servers sadly exist, hence the following.
629   (let ((str-processed (elpher-preprocess-text-response string)))
630     (dolist (line (split-string str-processed "\n"))
631       (ignore-errors
632         (unless (= (length line) 0)
633           (let* ((type (elt line 0))
634                  (fields (split-string (substring line 1) "\t"))
635                  (display-string (elt fields 0))
636                  (selector (elt fields 1))
637                  (host (elt fields 2))
638                  (port (if (elt fields 3)
639                            (string-to-number (elt fields 3))
640                          nil))
641                  (address (elpher-make-gopher-address type selector host port)))
642             (elpher-insert-index-record display-string address)))))))
643
644 (defun elpher-insert-margin (&optional type-name)
645   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
646   (if type-name
647       (progn
648         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
649                         (concat
650                          (propertize "[" 'face 'elpher-margin-brackets)
651                          (propertize type-name 'face 'elpher-margin-key)
652                          (propertize "]" 'face 'elpher-margin-brackets))))
653         (insert " "))
654     (insert (make-string elpher-margin-width ?\s))))
655
656 (defun elpher-page-button-help (page)
657   "Return a string containing the help text for a button corresponding to PAGE."
658   (let ((address (elpher-page-address page)))
659     (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
660                                           address
661                                         (elpher-address-to-url address)))))
662
663 (defun elpher-insert-index-record (display-string &optional address)
664   "Function to insert an index record into the current buffer.
665 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
666 If ADDRESS is not supplied or nil the record is rendered as an
667 'information' line."
668   (let* ((type (if address (elpher-address-type address) nil))
669          (type-map-entry (cdr (assoc type elpher-type-map))))
670     (if type-map-entry
671         (let* ((margin-code (elt type-map-entry 2))
672                (face (elt type-map-entry 3))
673                (filtered-display-string (ansi-color-filter-apply display-string))
674                (page (elpher-make-page filtered-display-string address)))
675           (elpher-insert-margin margin-code)
676           (insert-text-button filtered-display-string
677                               'face face
678                               'elpher-page page
679                               'action #'elpher-click-link
680                               'follow-link t
681                               'help-echo (elpher-page-button-help page)))
682       (pcase type
683         ((or '(gopher ?i) 'nil) ;; Information
684          (elpher-insert-margin)
685          (let ((propertized-display-string
686                 (propertize display-string 'face 'elpher-info)))
687            (insert (elpher-process-text-for-display propertized-display-string))))
688         (`(gopher ,selector-type) ;; Unknown
689          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
690          (insert (propertize display-string
691                              'face 'elpher-unknown)))))
692     (insert "\n")))
693
694 (defun elpher-click-link (button)
695   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
696   (let ((page (button-get button 'elpher-page)))
697     (elpher-visit-page page)))
698
699 (defun elpher-render-index (data &optional _mime-type-string)
700   "Render DATA as an index.  MIME-TYPE-STRING is unused."
701   (elpher-with-clean-buffer
702    (if (not data)
703        t
704      (elpher-insert-index data)
705      (elpher-cache-content (elpher-page-address elpher-current-page)
706                            (buffer-string)))))
707
708 ;; Text rendering
709
710 (defconst elpher-url-regex
711   "\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.\-]*[a-zA-Z0-9\-]\\|\[[a-zA-Z0-9:]+\]\\)\\(:[0-9]+\\)?\\(/\\([0-9a-zA-Z\-_~?/@|:.%#=&]*[0-9a-zA-Z\-_~?/@|#]\\)?\\)?"
712   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
713
714 (defun elpher-buttonify-urls (string)
715   "Turn substrings which look like urls in STRING into clickable buttons."
716   (with-temp-buffer
717     (insert string)
718     (goto-char (point-min))
719     (while (re-search-forward elpher-url-regex nil t)
720       (let ((page (elpher-make-page (substring-no-properties (match-string 0))
721                                     (elpher-address-from-url (match-string 0)))))
722           (make-text-button (match-beginning 0)
723                             (match-end 0)
724                             'elpher-page  page
725                             'action #'elpher-click-link
726                             'follow-link t
727                             'help-echo (elpher-page-button-help page)
728                             'face 'button)))
729     (buffer-string)))
730
731 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
732   "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
733
734 (defun elpher-process-text-for-display (string)
735   "Perform any desired processing of STRING prior to display as text.
736 Currently includes buttonifying URLs and processing ANSI escape codes."
737   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
738                              (ansi-color-filter-apply string)
739                            (ansi-color-apply string))))
740
741 (defun elpher-render-text (data &optional _mime-type-string)
742   "Render DATA as text.  MIME-TYPE-STRING is unused."
743   (elpher-with-clean-buffer
744    (if (not data)
745        t
746      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
747      (elpher-cache-content
748       (elpher-page-address elpher-current-page)
749       (buffer-string)))))
750
751 ;; Image retrieval
752
753 (defun elpher-render-image (data &optional _mime-type-string)
754   "Display DATA as image.  MIME-TYPE-STRING is unused."
755   (if (not data)
756       nil
757     (if (display-images-p)
758         (progn
759           (let ((image (create-image
760                         data
761                         nil t)))
762             (elpher-with-clean-buffer
763              (insert-image image)
764              (elpher-restore-pos))))
765       (elpher-render-download data))))
766
767 ;; Search retrieval and rendering
768
769 (defun elpher-get-gopher-query-page (renderer)
770   "Getter for gopher addresses requiring input.
771 The response is rendered using the rendering function RENDERER."
772    (let* ((address (elpher-page-address elpher-current-page))
773           (content (elpher-get-cached-content address))
774           (aborted t))
775     (if (and content (funcall renderer nil))
776         (elpher-with-clean-buffer
777          (insert content)
778          (elpher-restore-pos)
779          (message "Displaying cached search results.  Reload to perform a new search."))
780       (unwind-protect
781           (let* ((query-string (read-string "Query: "))
782                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
783                  (search-address (elpher-make-gopher-address ?1
784                                                              query-selector
785                                                              (elpher-address-host address)
786                                                              (elpher-address-port address)
787                                                              (equal (elpher-address-type address) "gophers"))))
788             (setq aborted nil)
789
790             (elpher-with-clean-buffer
791              (insert "LOADING RESULTS... (use 'u' to cancel)"))
792             (elpher-get-selector search-address renderer))
793         (if aborted
794             (elpher-visit-previous-page))))))
795  
796 ;; Raw server response rendering
797
798 (defun elpher-render-raw (data &optional mime-type-string)
799   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
800   (if (not data)
801       nil
802     (elpher-with-clean-buffer
803      (when mime-type-string
804        (insert "MIME type specified by server: '" mime-type-string "'\n"))
805      (insert data)
806      (goto-char (point-min)))
807     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
808
809 ;; File save "rendering"
810
811 (defun elpher-render-download (data &optional _mime-type-string)
812   "Save DATA to file.  MIME-TYPE-STRING is unused."
813   (if (not data)
814       nil
815     (let* ((address (elpher-page-address elpher-current-page))
816            (selector (if (elpher-address-gopher-p address)
817                          (elpher-gopher-address-selector address)
818                        (elpher-address-filename address))))
819       (elpher-visit-previous-page) ; Do first in case of non-local exits.
820       (let* ((filename-proposal (file-name-nondirectory selector))
821              (filename (read-file-name "Download complete. Save file as: "
822                                        nil nil nil
823                                        (if (> (length filename-proposal) 0)
824                                            filename-proposal
825                                          "download.file"))))
826         (let ((coding-system-for-write 'binary))
827           (with-temp-file filename
828             (insert data)))
829         (message (format "Saved to file %s." filename))))))
830
831 ;; HTML rendering
832
833 (defun elpher-render-html (data &optional _mime-type-string)
834   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
835   (elpher-with-clean-buffer
836    (if (not data)
837        t
838      (let ((dom (with-temp-buffer
839                   (insert data)
840                   (libxml-parse-html-region (point-min) (point-max)))))
841        (shr-insert-document dom)))))
842
843 ;; Gemini page retrieval
844
845 (defvar elpher-gemini-redirect-chain)
846
847 (defun elpher-get-gemini-response (address renderer &optional force-ipv4)
848   "Retrieve gemini ADDRESS, then render using RENDERER.
849 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
850 to ADDRESS."
851   (unless elpher-gemini-TLS-cert-checks
852     (setq-local network-security-level 'low))
853   (if (not (gnutls-available-p))
854       (error "Cannot establish gemini connection: GnuTLS not available")
855     (unless (< (elpher-address-port address) 65536)
856       (error "Cannot establish gemini connection: port number > 65536"))
857     (condition-case nil
858         (let* ((kill-buffer-query-functions nil)
859                (port (elpher-address-port address))
860                (host (elpher-address-host address))
861                (response-string-parts nil)
862                (proc (open-network-stream "elpher-process"
863                                           nil
864                                           (if force-ipv4 (dns-query host) host)
865                                           (if (> port 0) port 1965)
866                                           :type 'tls
867                                           :nowait t))
868                (timer (run-at-time elpher-connection-timeout nil
869                                    (lambda ()
870                                      (elpher-process-cleanup)
871                                      (unless force-ipv4
872                                         ; Try again with IPv4
873                                        (message "Connection timed out.  Retrying with IPv4.")
874                                        (elpher-get-gemini-response address renderer t))))))
875           (setq elpher-network-timer timer)
876           (set-process-coding-system proc 'binary)
877           (set-process-filter proc
878                               (lambda (_proc string)
879                                 (when timer
880                                   (cancel-timer timer)
881                                   (setq timer nil))
882                                 (setq response-string-parts
883                                       (cons string response-string-parts))))
884           (set-process-sentinel proc
885                                 (lambda (proc event)
886                                   (condition-case the-error
887                                       (cond
888                                        ((string-prefix-p "open" event)    ; request URL
889                                         (let ((inhibit-eol-conversion t))
890                                           (process-send-string
891                                            proc
892                                            (concat (elpher-address-to-url address)
893                                                    "\r\n"))))
894                                        ((string-prefix-p "deleted" event)) ; do nothing
895                                        ((and (not response-string-parts)
896                                              (not force-ipv4))
897                                         ; Try again with IPv4
898                                         (message "Connection failed. Retrying with IPv4.")
899                                         (cancel-timer timer)
900                                         (elpher-get-gemini-response address renderer t))
901                                        (t
902                                         (funcall #'elpher-process-gemini-response
903                                                  (apply #'concat (reverse response-string-parts))
904                                                  renderer)
905                                         (elpher-restore-pos)))
906                                     (error
907                                            (elpher-network-error address the-error))))))
908       (error
909        (error "Error initiating connection to server")))))
910
911 (defun elpher-parse-gemini-response (response)
912   "Parse the RESPONSE string and return a list of components.
913 The list is of the form (code meta body).  A response of nil implies
914 that the response was malformed."
915   (let ((header-end-idx (string-match "\r\n" response)))
916     (if header-end-idx
917         (let ((header (string-trim (substring response 0 header-end-idx)))
918               (body (substring response (+ header-end-idx 2))))
919           (if (>= (length header) 2)
920               (let ((code (substring header 0 2))
921                     (meta (string-trim (substring header 2))))
922                 (list code meta body))
923             (error "Malformed response: No response status found in header %s" header)))
924       (error "Malformed response: No CRLF-delimited header found"))))
925
926 (defun elpher-process-gemini-response (response-string renderer)
927   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
928   (let ((response-components (elpher-parse-gemini-response response-string)))
929     (let ((response-code (elt response-components 0))
930           (response-meta (elt response-components 1))
931           (response-body (elt response-components 2)))
932       (pcase (elt response-code 0)
933         (?1 ; Input required
934          (elpher-with-clean-buffer
935           (insert "Gemini server is requesting input."))
936          (let* ((query-string (read-string (concat response-meta ": ")))
937                 (url (elpher-address-to-url (elpher-page-address elpher-current-page)))
938                 (query-address (elpher-address-from-url (concat url "?" query-string))))
939            (elpher-get-gemini-response query-address renderer)))
940         (?2 ; Normal response
941          (funcall renderer response-body response-meta))
942         (?3 ; Redirect
943          (message "Following redirect to %s" response-meta)
944          (if (>= (length elpher-gemini-redirect-chain) 5)
945              (error "More than 5 consecutive redirects followed"))
946          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
947            (if (member redirect-address elpher-gemini-redirect-chain)
948                (error "Redirect loop detected"))
949            (if (not (string= (elpher-address-protocol redirect-address)
950                              "gemini"))
951                (error "Server tried to automatically redirect to non-gemini URL: %s"
952                       response-meta))
953            (elpher-page-set-address elpher-current-page redirect-address)
954            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
955            (elpher-get-gemini-response redirect-address renderer)))
956         (?4 ; Temporary failure
957          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
958                 response-code response-meta))
959         (?5 ; Permanent failure
960          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
961                 response-code response-meta))
962         (?6 ; Client certificate required
963          (error "Gemini server requires client certificate (unsupported at this time)"))
964         (_other
965          (error "Gemini server response unknown: %s %s"
966                 response-code response-meta))))))
967
968 (defun elpher-get-gemini-page (renderer)
969   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
970   (let* ((address (elpher-page-address elpher-current-page))
971          (content (elpher-get-cached-content address)))
972     (condition-case the-error
973         (if (and content (funcall renderer nil))
974             (elpher-with-clean-buffer
975               (insert content)
976               (elpher-restore-pos))
977           (elpher-with-clean-buffer
978            (insert "LOADING GEMINI... (use 'u' to cancel)"))
979           (setq elpher-gemini-redirect-chain nil)
980           (elpher-get-gemini-response address renderer))
981       (error
982        (elpher-network-error address the-error)))))
983
984
985 (defun elpher-render-gemini (body &optional mime-type-string)
986   "Render gemini response BODY with rendering MIME-TYPE-STRING."
987   (if (not body)
988       t
989     (let* ((mime-type-string* (if (or (not mime-type-string)
990                                       (string-empty-p mime-type-string))
991                                   "text/gemini; charset=utf-8"
992                                 mime-type-string))
993            (mime-type-split (split-string mime-type-string* ";" t))
994            (mime-type (string-trim (car mime-type-split)))
995            (parameters (mapcar (lambda (s)
996                                  (let ((key-val (split-string s "=")))
997                                    (list (downcase (string-trim (car key-val)))
998                                          (downcase (string-trim (cadr key-val))))))
999                                (cdr mime-type-split))))
1000       (when (string-prefix-p "text/" mime-type)
1001         (setq body (decode-coding-string
1002                     body
1003                     (if (assoc "charset" parameters)
1004                         (intern (cadr (assoc "charset" parameters)))
1005                       'utf-8)))
1006         (setq body (replace-regexp-in-string "\r" "" body)))
1007       (pcase mime-type
1008         ((or "text/gemini" "")
1009          (elpher-render-gemini-map body parameters))
1010         ("text/html"
1011          (elpher-render-html body))
1012         ((pred (string-prefix-p "text/"))
1013          (elpher-render-gemini-plain-text body parameters))
1014         ((pred (string-prefix-p "image/"))
1015          (elpher-render-image body))
1016         (_other
1017          (error "Unsupported MIME type %S" mime-type))))))
1018
1019 (defun elpher-gemini-get-link-url (link-line)
1020   "Extract the url portion of LINK-LINE, a gemini map file link line.
1021 Returns nil in the event that the contents of the line following the
1022 => prefix are empty."
1023   (let ((l (split-string (substring link-line 2))))
1024     (if l
1025         (string-trim (elt l 0))
1026       nil)))
1027
1028 (defun elpher-gemini-get-link-display-string (link-line)
1029   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1030 Returns the url portion in the event that the display-string portion is empty."
1031   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1032          (idx (string-match "[ \t]" rest)))
1033     (string-trim (if idx
1034                      (substring rest (+ idx 1))
1035                    rest))))
1036
1037 (defun elpher-collapse-dot-sequences (filename)
1038   "Collapse dot sequences in FILENAME.
1039 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1040   (let* ((path (split-string filename "/"))
1041          (path-reversed-normalized
1042           (seq-reduce (lambda (a b)
1043                         (cond ((and a (equal b "..") (cdr a)))
1044                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
1045                               ((equal b ".") a)
1046                               (t (cons b a))))
1047                       path nil)))
1048     (string-join (reverse path-reversed-normalized) "/")))
1049
1050 (defun elpher-address-from-gemini-url (url)
1051   "Extract address from URL with defaults as per gemini map files."
1052   (let ((address (url-generic-parse-url url)))
1053     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1054       (setf (url-fullness address) t)
1055       (if (url-host address) ;if there is an explicit host, filenames are absolute
1056           (if (string-empty-p (url-filename address))
1057               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1058         (setf (url-host address) (url-host (elpher-page-address elpher-current-page)))
1059         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1060           (setf (url-filename address)
1061                 (concat (file-name-directory
1062                          (url-filename (elpher-page-address elpher-current-page)))
1063                         (url-filename address)))))
1064       (unless (url-type address)
1065         (setf (url-type address) "gemini"))
1066       (if (equal (url-type address) "gemini")
1067           (setf (url-filename address)
1068                 (elpher-collapse-dot-sequences (url-filename address)))))
1069     address))
1070
1071 (defun elpher-gemini-insert-link (link-line)
1072   "Insert link described by LINK-LINE into a text/gemini document."
1073   (let* ((url (elpher-gemini-get-link-url link-line))
1074          (display-string (elpher-gemini-get-link-display-string link-line))
1075          (address (elpher-address-from-gemini-url url))
1076          (type (if address (elpher-address-type address) nil))
1077          (type-map-entry (cdr (assoc type elpher-type-map))))
1078     (when display-string
1079       (insert "→ ")
1080       (if type-map-entry
1081           (let* ((face (elt type-map-entry 3))
1082                  (filtered-display-string (ansi-color-filter-apply display-string))
1083                  (page (elpher-make-page filtered-display-string address)))
1084             (insert-text-button filtered-display-string
1085                                 'face face
1086                                 'elpher-page page
1087                                 'action #'elpher-click-link
1088                                 'follow-link t
1089                                 'help-echo (elpher-page-button-help page)))
1090         (insert (propertize display-string 'face 'elpher-unknown)))
1091       (insert "\n"))))
1092   
1093 (defun elpher-gemini-insert-header (header-line)
1094   "Insert header described by HEADER-LINE into a text/gemini document.
1095 The gemini map file line describing the header is given
1096 by HEADER-LINE."
1097   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1098     (let ((level (length (match-string 1 header-line)))
1099           (header (substring header-line (match-end 0))))
1100       (unless (display-graphic-p)
1101         (insert (make-string level ?#) " "))
1102       (insert (propertize header 'face
1103                           (pcase level
1104                             (1 'elpher-gemini-heading1)
1105                             (2 'elpher-gemini-heading2)
1106                             (3 'elpher-gemini-heading3)
1107                             (_ 'default)))
1108               "\n"))))
1109
1110 (defun elpher-render-gemini-map (data _parameters)
1111   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1112   (elpher-with-clean-buffer
1113    (let ((preformatted nil))
1114      (auto-fill-mode 1)
1115      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1116      (dolist (line (split-string data "\n"))
1117        (cond
1118         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1119         (preformatted (insert (elpher-process-text-for-display line) "\n"))
1120         ((string-prefix-p "=>" line) (elpher-gemini-insert-link line))
1121         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1122         (t (insert (elpher-process-text-for-display line)) (newline)))))
1123    (elpher-cache-content
1124     (elpher-page-address elpher-current-page)
1125     (buffer-string))))
1126
1127 (defun elpher-render-gemini-plain-text (data _parameters)
1128   "Render DATA as plain text file.  PARAMETERS is currently unused."
1129   (elpher-with-clean-buffer
1130    (insert (elpher-process-text-for-display data))
1131    (elpher-cache-content
1132     (elpher-page-address elpher-current-page)
1133     (buffer-string))))
1134
1135 ;; Finger page connection
1136
1137 (defun elpher-get-finger-page (renderer &optional force-ipv4)
1138   "Opens a finger connection to the current page address and renders it using RENDERER."
1139   (let* ((address (elpher-page-address elpher-current-page))
1140          (content (elpher-get-cached-content address)))
1141     (if (and content (funcall renderer nil))
1142         (elpher-with-clean-buffer
1143          (insert content)
1144          (elpher-restore-pos))
1145       (elpher-with-clean-buffer
1146        (insert "LOADING... (use 'u' to cancel)"))
1147       (condition-case the-error
1148           (let* ((kill-buffer-query-functions nil)
1149                  (user (let ((filename (elpher-address-filename address)))
1150                          (if (> (length filename) 1)
1151                              (substring filename 1)
1152                            (elpher-address-user address))))
1153                  (port (let ((given-port (elpher-address-port address)))
1154                          (if (> given-port 0) given-port 79)))
1155                  (host (elpher-address-host address))
1156                  (selector-string-parts nil)
1157                  (proc (open-network-stream "elpher-process"
1158                                             nil
1159                                             (if force-ipv4 (dns-query host) host)
1160                                             port
1161                                             :type 'plain
1162                                             :nowait t))
1163                  (timer (run-at-time elpher-connection-timeout
1164                                      nil
1165                                      (lambda ()
1166                                        (pcase (process-status proc)
1167                                          ('connect
1168                                           (elpher-process-cleanup)
1169                                           (unless force-ipv4
1170                                             (message "Connection timed out. Retrying with IPv4 address.")
1171                                             (elpher-get-finger-page renderer t))))))))
1172             (setq elpher-network-timer timer)
1173             (set-process-coding-system proc 'binary)
1174             (set-process-filter proc
1175                                 (lambda (_proc string)
1176                                   (cancel-timer timer)
1177                                   (setq selector-string-parts
1178                                         (cons string selector-string-parts))))
1179             (set-process-sentinel proc
1180                                   (lambda (_proc event)
1181                                     (condition-case the-error
1182                                         (cond
1183                                          ((string-prefix-p "deleted" event))
1184                                          ((string-prefix-p "open" event)
1185                                           (let ((inhibit-eol-conversion t))
1186                                             (process-send-string
1187                                              proc
1188                                              (concat user "\r\n"))))
1189                                          (t
1190                                           (cancel-timer timer)
1191                                           (funcall renderer (apply #'concat
1192                                                                    (reverse selector-string-parts)))
1193                                           (elpher-restore-pos)))))))
1194         (error
1195          (elpher-network-error address the-error))))))
1196
1197
1198 ;; Other URL page opening
1199
1200 (defun elpher-get-other-url-page (renderer)
1201   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1202   (when renderer
1203     (elpher-visit-previous-page)
1204     (error "Command not supported for general URLs"))
1205   (let* ((address (elpher-page-address elpher-current-page))
1206          (url (elpher-address-to-url address)))
1207     (progn
1208       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1209       (message "Opening URL...")
1210       (if elpher-open-urls-with-eww
1211           (browse-web url)
1212         (browse-url url)))))
1213
1214 ;; Telnet page connection
1215
1216 (defun elpher-get-telnet-page (renderer)
1217   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1218   (when renderer
1219     (elpher-visit-previous-page)
1220     (error "Command not supported for telnet URLs"))
1221   (let* ((address (elpher-page-address elpher-current-page))
1222          (host (elpher-address-host address))
1223          (port (elpher-address-port address)))
1224     (elpher-visit-previous-page)
1225     (if (> port 0)
1226         (telnet host port)
1227       (telnet host))))
1228
1229 ;; Start page page retrieval
1230
1231 (defun elpher-get-start-page (renderer)
1232   "Getter which displays the start page (RENDERER must be nil)."
1233   (when renderer
1234     (elpher-visit-previous-page)
1235     (error "Command not supported for start page"))
1236   (elpher-with-clean-buffer
1237    (insert "     --------------------------------------------\n"
1238            "                Elpher Gopher Client             \n"
1239            "                   version " elpher-version "\n"
1240            "     --------------------------------------------\n"
1241            "\n"
1242            "Default bindings:\n"
1243            "\n"
1244            " - TAB/Shift-TAB: next/prev item on current page\n"
1245            " - RET/mouse-1: open item under cursor\n"
1246            " - m: select an item on current page by name (autocompletes)\n"
1247            " - u/mouse-3: return to previous page\n"
1248            " - o/O: visit different selector or the root menu of the current server\n"
1249            " - g: go to a particular gopher address\n"
1250            " - d/D: download item under cursor or current page\n"
1251            " - i/I: info on item under cursor or current page\n"
1252            " - c/C: copy URL representation of item under cursor or current page\n"
1253            " - a/A: bookmark the item under cursor or current page\n"
1254            " - x/X: remove bookmark for item under cursor or current page\n"
1255            " - B: visit the bookmarks page\n"
1256            " - r: redraw current page (using cached contents if available)\n"
1257            " - R: reload current page (regenerates cache)\n"
1258            " - S: set character coding system for gopher (default is to autodetect)\n"
1259            " - T: toggle TLS gopher mode\n"
1260            " - .: display the raw server response for the current page\n"
1261            "\n"
1262            "Start your exploration of gopher space:\n")
1263    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1264                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1265    (insert "\n"
1266            "Alternatively, select the following item and enter some search terms:\n")
1267    (elpher-insert-index-record "Veronica-2 Gopher Search Engine"
1268                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1269    (insert "\n"
1270            "This page contains your bookmarked sites (also visit with B):\n")
1271    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1272    (insert "\n"
1273            "For Elpher release news or to leave feedback, visit:\n")
1274    (elpher-insert-index-record "The Elpher Project Page"
1275                                (elpher-make-gopher-address ?1
1276                                                            "/projects/elpher/"
1277                                                            "thelambdalab.xyz"
1278                                                            70))
1279    (insert "\n"
1280            "** Refer to the ")
1281    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1282      (insert-text-button "Elpher info manual"
1283                          'face 'link
1284                          'action (lambda (_)
1285                                    (interactive)
1286                                    (info "(elpher)"))
1287                          'follow-link t
1288                          'help-echo help-string))
1289    (insert " for the full documentation. **\n")
1290    (insert (propertize
1291             (concat "  (This should be available if you have installed Elpher using\n"
1292                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1293             'face 'shadow))
1294    (elpher-restore-pos)))
1295
1296 ;; Bookmarks page page retrieval
1297
1298 (defun elpher-get-bookmarks-page (renderer)
1299   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1300   (when renderer
1301     (elpher-visit-previous-page)
1302     (error "Command not supported for bookmarks page"))
1303   (elpher-with-clean-buffer
1304    (insert "---- Bookmark list ----\n\n")
1305    (let ((bookmarks (elpher-load-bookmarks)))
1306      (if bookmarks
1307          (dolist (bookmark bookmarks)
1308            (let ((display-string (elpher-bookmark-display-string bookmark))
1309                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1310              (elpher-insert-index-record display-string address)))
1311        (insert "No bookmarks found.\n")))
1312    (insert "\n-----------------------\n"
1313            "\n"
1314            "- u: return to previous page\n"
1315            "- x: delete selected bookmark\n"
1316            "- a: rename selected bookmark\n"
1317            "\n"
1318            "Bookmarks are stored in the file ")
1319    (let ((filename elpher-bookmarks-file)
1320          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1321      (insert-text-button filename
1322                          'face 'link
1323                          'action (lambda (_)
1324                                    (interactive)
1325                                    (find-file filename))
1326                          'follow-link t
1327                          'help-echo help-string))
1328    (insert "\n")
1329    (elpher-restore-pos)))
1330   
1331
1332 ;;; Bookmarks
1333 ;;
1334
1335 (defun elpher-make-bookmark (display-string url)
1336   "Make an elpher bookmark.
1337 DISPLAY-STRING determines how the bookmark will appear in the
1338 bookmark list, while URL is the url of the entry."
1339   (list display-string url))
1340   
1341 (defun elpher-bookmark-display-string (bookmark)
1342   "Get the display string of BOOKMARK."
1343   (elt bookmark 0))
1344
1345 (defun elpher-set-bookmark-display-string (bookmark display-string)
1346   "Set the display string of BOOKMARK to DISPLAY-STRING."
1347   (setcar bookmark display-string))
1348
1349 (defun elpher-bookmark-url (bookmark)
1350   "Get the address for BOOKMARK."
1351   (elt bookmark 1))
1352
1353 (defun elpher-save-bookmarks (bookmarks)
1354   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1355 Beware that this completely replaces the existing contents of the file."
1356   (with-temp-file elpher-bookmarks-file
1357     (erase-buffer)
1358     (insert "; Elpher bookmarks file\n\n"
1359             "; Bookmarks are stored as a list of (label URL) items.\n"
1360             "; Feel free to edit by hand, but take care to ensure\n"
1361             "; the list structure remains intact.\n\n")
1362     (pp bookmarks (current-buffer))))
1363
1364 (defun elpher-load-bookmarks ()
1365   "Get the list of bookmarks from the users's bookmark file."
1366   (let ((bookmarks
1367          (with-temp-buffer
1368            (ignore-errors
1369              (insert-file-contents elpher-bookmarks-file)
1370              (goto-char (point-min))
1371              (read (current-buffer))))))
1372     (if (and bookmarks (listp (cadar bookmarks)))
1373         (progn
1374           (message "Reading old bookmark file. (Will be updated on write.)")
1375           (mapcar (lambda (old-bm)
1376                     (list (car old-bm)
1377                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1378                                                         (cadr old-bm)))))
1379                   bookmarks))
1380       bookmarks)))
1381
1382 (defun elpher-add-address-bookmark (address display-string)
1383   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1384 If ADDRESS is already bookmarked, update the label only."
1385   (let ((bookmarks (elpher-load-bookmarks))
1386         (url (elpher-address-to-url address)))
1387     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1388       (if existing-bookmark
1389           (elpher-set-bookmark-display-string existing-bookmark display-string)
1390         (push (elpher-make-bookmark display-string url) bookmarks)))
1391     (elpher-save-bookmarks bookmarks)))
1392
1393 (defun elpher-remove-address-bookmark (address)
1394   "Remove any bookmark to ADDRESS."
1395   (let ((url (elpher-address-to-url address)))
1396     (elpher-save-bookmarks
1397      (seq-filter (lambda (bookmark)
1398                    (not (equal (elpher-bookmark-url bookmark) url)))
1399                  (elpher-load-bookmarks)))))
1400
1401 ;;; Interactive procedures
1402 ;;
1403
1404 (defun elpher-next-link ()
1405   "Move point to the next link on the current page."
1406   (interactive)
1407   (forward-button 1))
1408
1409 (defun elpher-prev-link ()
1410   "Move point to the previous link on the current page."
1411   (interactive)
1412   (backward-button 1))
1413
1414 (defun elpher-follow-current-link ()
1415   "Open the link or url at point."
1416   (interactive)
1417   (push-button))
1418
1419 (defun elpher-go (host-or-url)
1420   "Go to a particular gopher site HOST-OR-URL.
1421 When run interactively HOST-OR-URL is read from the minibuffer."
1422   (interactive "sGopher or Gemini URL: ")
1423   (let ((page (elpher-make-page host-or-url
1424                                 (elpher-address-from-url host-or-url))))
1425     (switch-to-buffer "*elpher*")
1426     (elpher-visit-page page)
1427     '()))
1428
1429 (defun elpher-go-current ()
1430   "Go to a particular site read from the minibuffer, initialized with the current URL."
1431   (interactive)
1432   (let ((address (elpher-page-address elpher-current-page)))
1433     (if (elpher-address-special-p address)
1434         (error "Command invalid for this page")
1435       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1436         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1437
1438 (defun elpher-redraw ()
1439   "Redraw current page."
1440   (interactive)
1441   (elpher-visit-page elpher-current-page))
1442
1443 (defun elpher-reload ()
1444   "Reload current page."
1445   (interactive)
1446   (elpher-reload-current-page))
1447
1448 (defun elpher-toggle-tls ()
1449   "Toggle TLS encryption mode for gopher."
1450   (interactive)
1451   (setq elpher-use-tls (not elpher-use-tls))
1452   (if elpher-use-tls
1453       (if (gnutls-available-p)
1454           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1455         (setq elpher-use-tls nil)
1456         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1457     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1458
1459 (defun elpher-view-raw ()
1460   "View raw server response for current page."
1461   (interactive)
1462   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1463       (error "This page was not generated by a server")
1464     (elpher-visit-page elpher-current-page
1465                        #'elpher-render-raw)))
1466
1467 (defun elpher-back ()
1468   "Go to previous site."
1469   (interactive)
1470   (elpher-visit-previous-page))
1471
1472 (defun elpher-download ()
1473   "Download the link at point."
1474   (interactive)
1475   (let ((button (button-at (point))))
1476     (if button
1477         (let ((page (button-get button 'elpher-page)))
1478           (if (elpher-address-special-p (elpher-page-address page))
1479               (error "Cannot download %s"
1480                      (elpher-page-display-string page))
1481             (elpher-visit-page (button-get button 'elpher-page)
1482                                #'elpher-render-download)))
1483       (error "No link selected"))))
1484
1485 (defun elpher-download-current ()
1486   "Download the current page."
1487   (interactive)
1488   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1489       (error "Cannot download %s"
1490              (elpher-page-display-string elpher-current-page))
1491     (elpher-visit-page (elpher-make-page
1492                         (elpher-page-display-string elpher-current-page)
1493                         (elpher-page-address elpher-current-page))
1494                        #'elpher-render-download
1495                        t)))
1496
1497 (defun elpher-build-link-map ()
1498   "Build alist mapping link names to destination pages in current buffer."
1499   (let ((link-map nil)
1500         (b (next-button (point-min) t)))
1501     (while b
1502       (push (cons (button-label b) b) link-map)
1503       (setq b (next-button (button-start b))))
1504     link-map))
1505
1506 (defun elpher-jump ()
1507   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1508   (interactive)
1509   (let* ((link-map (elpher-build-link-map)))
1510     (if link-map
1511         (let ((key (let ((completion-ignore-case t))
1512                      (completing-read "Directory item/link: "
1513                                       link-map nil t))))
1514           (if (and key (> (length key) 0))
1515               (let ((b (cdr (assoc key link-map))))
1516                 (goto-char (button-start b))
1517                 (button-activate b)))))))
1518
1519 (defun elpher-root-dir ()
1520   "Visit root of current server."
1521   (interactive)
1522   (let ((address (elpher-page-address elpher-current-page)))
1523     (if (not (elpher-address-special-p address))
1524         (if (or (member (url-filename address) '("/" ""))
1525                 (and (elpher-address-gopher-p address)
1526                      (= (length (elpher-gopher-address-selector address)) 0)))
1527             (error "Already at root directory of current server")
1528           (let ((address-copy (elpher-address-from-url
1529                                (elpher-address-to-url address))))
1530             (setf (url-filename address-copy) "")
1531             (elpher-go (elpher-address-to-url address-copy))))
1532       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1533
1534 (defun elpher-bookmarks-current-p ()
1535   "Return non-nil if current page is a bookmarks page."
1536   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1537          '(special bookmarks)))
1538
1539 (defun elpher-reload-bookmarks ()
1540   "Reload bookmarks if current page is a bookmarks page."
1541   (if (elpher-bookmarks-current-p)
1542       (elpher-reload-current-page)))
1543
1544 (defun elpher-bookmark-current ()
1545   "Bookmark the current page."
1546   (interactive)
1547   (let ((address (elpher-page-address elpher-current-page))
1548         (display-string (elpher-page-display-string elpher-current-page)))
1549     (if (not (elpher-address-special-p address))
1550         (let ((bookmark-display-string (read-string "Bookmark display string: "
1551                                                     display-string)))
1552           (elpher-add-address-bookmark address bookmark-display-string)
1553           (message "Bookmark added."))
1554       (error "Cannot bookmark %s" display-string))))
1555
1556 (defun elpher-bookmark-link ()
1557   "Bookmark the link at point."
1558   (interactive)
1559   (let ((button (button-at (point))))
1560     (if button
1561         (let* ((page (button-get button 'elpher-page))
1562                (address (elpher-page-address page))
1563                (display-string (elpher-page-display-string page)))
1564           (if (not (elpher-address-special-p address))
1565               (let ((bookmark-display-string (read-string "Bookmark display string: "
1566                                                           display-string)))
1567                 (elpher-add-address-bookmark address bookmark-display-string)
1568                 (elpher-reload-bookmarks)
1569                 (message "Bookmark added."))
1570             (error "Cannot bookmark %s" display-string)))
1571       (error "No link selected"))))
1572
1573 (defun elpher-unbookmark-current ()
1574   "Remove bookmark for the current page."
1575   (interactive)
1576   (let ((address (elpher-page-address elpher-current-page)))
1577     (unless (elpher-address-special-p address)
1578       (elpher-remove-address-bookmark address)
1579       (message "Bookmark removed."))))
1580
1581 (defun elpher-unbookmark-link ()
1582   "Remove bookmark for the link at point."
1583   (interactive)
1584   (let ((button (button-at (point))))
1585     (if button
1586         (let ((page (button-get button 'elpher-page)))
1587           (elpher-remove-address-bookmark (elpher-page-address page))
1588           (elpher-reload-bookmarks)
1589           (message "Bookmark removed."))
1590       (error "No link selected"))))
1591
1592 (defun elpher-bookmarks ()
1593   "Visit bookmarks page."
1594   (interactive)
1595   (switch-to-buffer "*elpher*")
1596   (elpher-visit-page
1597    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1598
1599 (defun elpher-info-page (page)
1600   "Display information on PAGE."
1601   (let ((display-string (elpher-page-display-string page))
1602         (address (elpher-page-address page)))
1603     (if (elpher-address-special-p address)
1604         (message "Special page: %s" display-string)
1605       (message "%s" (elpher-address-to-url address)))))
1606
1607 (defun elpher-info-link ()
1608   "Display information on page corresponding to link at point."
1609   (interactive)
1610   (let ((button (button-at (point))))
1611     (if button
1612         (elpher-info-page (button-get button 'elpher-page))
1613       (error "No item selected"))))
1614   
1615 (defun elpher-info-current ()
1616   "Display information on current page."
1617   (interactive)
1618   (elpher-info-page elpher-current-page))
1619
1620 (defun elpher-copy-page-url (page)
1621   "Copy URL representation of address of PAGE to `kill-ring'."
1622   (let ((address (elpher-page-address page)))
1623     (if (elpher-address-special-p address)
1624         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1625       (let ((url (elpher-address-to-url address)))
1626         (message "Copied \"%s\" to kill-ring/clipboard." url)
1627         (kill-new url)))))
1628
1629 (defun elpher-copy-link-url ()
1630   "Copy URL of item at point to `kill-ring'."
1631   (interactive)
1632   (let ((button (button-at (point))))
1633     (if button
1634         (elpher-copy-page-url (button-get button 'elpher-page))
1635       (error "No item selected"))))
1636
1637 (defun elpher-copy-current-url ()
1638   "Copy URL of current page to `kill-ring'."
1639   (interactive)
1640   (elpher-copy-page-url elpher-current-page))
1641
1642 (defun elpher-set-gopher-coding-system ()
1643   "Specify an explicit character coding system for gopher selectors."
1644   (interactive)
1645   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1646     (setq elpher-user-coding-system system)
1647     (if system
1648         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1649       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1650
1651
1652 ;;; Mode and keymap
1653 ;;
1654
1655 (defvar elpher-mode-map
1656   (let ((map (make-sparse-keymap)))
1657     (define-key map (kbd "TAB") 'elpher-next-link)
1658     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1659     (define-key map (kbd "u") 'elpher-back)
1660     (define-key map [mouse-3] 'elpher-back)
1661     (define-key map (kbd "O") 'elpher-root-dir)
1662     (define-key map (kbd "g") 'elpher-go)
1663     (define-key map (kbd "o") 'elpher-go-current)
1664     (define-key map (kbd "r") 'elpher-redraw)
1665     (define-key map (kbd "R") 'elpher-reload)
1666     (define-key map (kbd "T") 'elpher-toggle-tls)
1667     (define-key map (kbd ".") 'elpher-view-raw)
1668     (define-key map (kbd "d") 'elpher-download)
1669     (define-key map (kbd "D") 'elpher-download-current)
1670     (define-key map (kbd "m") 'elpher-jump)
1671     (define-key map (kbd "i") 'elpher-info-link)
1672     (define-key map (kbd "I") 'elpher-info-current)
1673     (define-key map (kbd "c") 'elpher-copy-link-url)
1674     (define-key map (kbd "C") 'elpher-copy-current-url)
1675     (define-key map (kbd "a") 'elpher-bookmark-link)
1676     (define-key map (kbd "A") 'elpher-bookmark-current)
1677     (define-key map (kbd "x") 'elpher-unbookmark-link)
1678     (define-key map (kbd "X") 'elpher-unbookmark-current)
1679     (define-key map (kbd "B") 'elpher-bookmarks)
1680     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1681     (when (fboundp 'evil-define-key*)
1682       (evil-define-key* 'motion map
1683         (kbd "TAB") 'elpher-next-link
1684         (kbd "C-") 'elpher-follow-current-link
1685         (kbd "C-t") 'elpher-back
1686         (kbd "u") 'elpher-back
1687         [mouse-3] 'elpher-back
1688         (kbd "g") 'elpher-go
1689         (kbd "o") 'elpher-go-current
1690         (kbd "r") 'elpher-redraw
1691         (kbd "R") 'elpher-reload
1692         (kbd "T") 'elpher-toggle-tls
1693         (kbd ".") 'elpher-view-raw
1694         (kbd "d") 'elpher-download
1695         (kbd "D") 'elpher-download-current
1696         (kbd "m") 'elpher-jump
1697         (kbd "i") 'elpher-info-link
1698         (kbd "I") 'elpher-info-current
1699         (kbd "c") 'elpher-copy-link-url
1700         (kbd "C") 'elpher-copy-current-url
1701         (kbd "a") 'elpher-bookmark-link
1702         (kbd "A") 'elpher-bookmark-current
1703         (kbd "x") 'elpher-unbookmark-link
1704         (kbd "X") 'elpher-unbookmark-current
1705         (kbd "B") 'elpher-bookmarks
1706         (kbd "S") 'elpher-set-gopher-coding-system))
1707     map)
1708   "Keymap for gopher client.")
1709
1710 (define-derived-mode elpher-mode special-mode "elpher"
1711   "Major mode for elpher, an elisp gopher client.
1712
1713 This mode is automatically enabled by the interactive
1714 functions which initialize the gopher client, namely
1715 `elpher', `elpher-go' and `elpher-bookmarks'.")
1716
1717 (when (fboundp 'evil-set-initial-state)
1718   (evil-set-initial-state 'elpher-mode 'motion))
1719
1720
1721 ;;; Main start procedure
1722 ;;
1723
1724 ;;;###autoload
1725 (defun elpher ()
1726   "Start elpher with default landing page."
1727   (interactive)
1728   (if (get-buffer "*elpher*")
1729       (switch-to-buffer "*elpher*")
1730     (switch-to-buffer "*elpher*")
1731     (setq elpher-current-page nil)
1732     (let ((start-page (elpher-make-page "Elpher Start Page"
1733                                         (elpher-make-special-address 'start))))
1734       (elpher-visit-page start-page)))
1735   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1736
1737 ;;; elpher.el ends here