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