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