Version bump.
[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                (page (elpher-make-page display-string address)))
623           (elpher-insert-margin margin-code)
624           (insert-text-button display-string
625                               'face face
626                               'elpher-page page
627                               'action #'elpher-click-link
628                               'follow-link t
629                               'help-echo (elpher-page-button-help page)))
630       (pcase type
631         ((or '(gopher ?i) 'nil) ;; Information
632          (elpher-insert-margin)
633          (let ((propertized-display-string
634                 (propertize display-string 'face 'elpher-info)))
635            (insert (elpher-process-text-for-display propertized-display-string))))
636         (`(gopher ,selector-type) ;; Unknown
637          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
638          (insert (propertize display-string
639                              'face 'elpher-unknown)))))
640     (insert "\n")))
641
642 (defun elpher-click-link (button)
643   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
644   (let ((page (button-get button 'elpher-page)))
645     (elpher-visit-page page)))
646
647 (defun elpher-render-index (data &optional _mime-type-string)
648   "Render DATA as an index.  MIME-TYPE-STRING is unused."
649   (elpher-with-clean-buffer
650    (if (not data)
651        t
652      (elpher-insert-index data)
653      (elpher-cache-content (elpher-page-address elpher-current-page)
654                            (buffer-string)))))
655
656 ;; Text rendering
657
658 (defconst elpher-url-regex
659   "\\([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\-_~?/@|#]\\)?\\)?"
660   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
661
662 (defun elpher-buttonify-urls (string)
663   "Turn substrings which look like urls in STRING into clickable buttons."
664   (with-temp-buffer
665     (insert string)
666     (goto-char (point-min))
667     (while (re-search-forward elpher-url-regex nil t)
668       (let ((page (elpher-make-page (substring-no-properties (match-string 0))
669                                     (elpher-address-from-url (match-string 0)))))
670           (make-text-button (match-beginning 0)
671                             (match-end 0)
672                             'elpher-page  page
673                             'action #'elpher-click-link
674                             'follow-link t
675                             'help-echo (elpher-page-button-help page)
676                             'face 'button)))
677     (buffer-string)))
678
679 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
680   "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
681
682 (defun elpher-process-text-for-display (string)
683   "Perform any desired processing of STRING prior to display as text.
684 Currently includes buttonifying URLs and processing ANSI escape codes."
685   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
686                              (ansi-color-filter-apply string)
687                            (ansi-color-apply string))))
688
689 (defun elpher-render-text (data &optional _mime-type-string)
690   "Render DATA as text.  MIME-TYPE-STRING is unused."
691   (elpher-with-clean-buffer
692    (if (not data)
693        t
694      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
695      (elpher-cache-content
696       (elpher-page-address elpher-current-page)
697       (buffer-string)))))
698
699 ;; Image retrieval
700
701 (defun elpher-render-image (data &optional _mime-type-string)
702   "Display DATA as image.  MIME-TYPE-STRING is unused."
703   (if (not data)
704       nil
705     (if (display-images-p)
706         (progn
707           (let ((image (create-image
708                         data
709                         nil t)))
710             (elpher-with-clean-buffer
711              (insert-image image)
712              (elpher-restore-pos))))
713       (elpher-render-download data))))
714
715 ;; Search retrieval and rendering
716
717 (defun elpher-get-gopher-query-page (renderer)
718   "Getter for gopher addresses requiring input.
719 The response is rendered using the rendering function RENDERER."
720    (let* ((address (elpher-page-address elpher-current-page))
721           (content (elpher-get-cached-content address))
722           (aborted t))
723     (if (and content (funcall renderer nil))
724         (elpher-with-clean-buffer
725          (insert content)
726          (elpher-restore-pos)
727          (message "Displaying cached search results.  Reload to perform a new search."))
728       (unwind-protect
729           (let* ((query-string (read-string "Query: "))
730                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
731                  (search-address (elpher-make-gopher-address ?1
732                                                              query-selector
733                                                              (elpher-address-host address)
734                                                              (elpher-address-port address)
735                                                              (equal (elpher-address-type address) "gophers"))))
736             (setq aborted nil)
737
738             (elpher-with-clean-buffer
739              (insert "LOADING RESULTS... (use 'u' to cancel)"))
740             (elpher-get-selector search-address renderer))
741         (if aborted
742             (elpher-visit-previous-page))))))
743  
744 ;; Raw server response rendering
745
746 (defun elpher-render-raw (data &optional mime-type-string)
747   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
748   (if (not data)
749       nil
750     (elpher-with-clean-buffer
751      (when mime-type-string
752        (insert "MIME type specified by server: '" mime-type-string "'\n"))
753      (insert data)
754      (goto-char (point-min)))
755     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
756
757 ;; File save "rendering"
758
759 (defun elpher-render-download (data &optional _mime-type-string)
760   "Save DATA to file.  MIME-TYPE-STRING is unused."
761   (if (not data)
762       nil
763     (let* ((address (elpher-page-address elpher-current-page))
764            (selector (elpher-gopher-address-selector address)))
765       (elpher-visit-previous-page) ; Do first in case of non-local exits.
766       (let* ((filename-proposal (file-name-nondirectory selector))
767              (filename (read-file-name "Download complete. Save file as: "
768                                        nil nil nil
769                                        (if (> (length filename-proposal) 0)
770                                            filename-proposal
771                                          "download.file"))))
772         (let ((coding-system-for-write 'binary))
773           (with-temp-file filename
774             (insert data)))
775         (message (format "Saved to file %s." filename))))))
776
777 ;; HTML rendering
778
779 (defun elpher-render-html (data &optional _mime-type-string)
780   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
781   (elpher-with-clean-buffer
782    (if (not data)
783        t
784      (let ((dom (with-temp-buffer
785                   (insert data)
786                   (libxml-parse-html-region (point-min) (point-max)))))
787        (shr-insert-document dom)))))
788
789 ;; Gemini page retrieval
790
791 (defvar elpher-gemini-redirect-chain)
792
793 (defun elpher-get-gemini-response (address renderer &optional force-ipv4)
794   "Retrieve gemini ADDRESS, then render using RENDERER.
795 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
796 to ADDRESS."
797   (if (not (gnutls-available-p))
798       (error "Cannot establish gemini connection: GnuTLS not available")
799     (unless (< (elpher-address-port address) 65536)
800       (error "Cannot establish gemini connection: port number > 65536"))
801     (condition-case nil
802         (let* ((kill-buffer-query-functions nil)
803                (port (elpher-address-port address))
804                (host (elpher-address-host address))
805                (response-string "")
806                (proc (open-network-stream "elpher-process"
807                                           nil
808                                           (if force-ipv4 (dns-query host) host)
809                                           (if (> port 0) port 1965)
810                                           :type 'tls
811                                           :nowait t))
812                (timer (run-at-time elpher-connection-timeout nil
813                                    (lambda ()
814                                      (elpher-process-cleanup)
815                                      (unless force-ipv4
816                                         ; Try again with IPv4
817                                        (message "Connection timed out.  Retrying with IPv4.")
818                                        (elpher-get-gemini-response address renderer t))))))
819           (setq elpher-network-timer timer)
820           (set-process-coding-system proc 'binary)
821           (set-process-filter proc
822                               (lambda (_proc string)
823                                 (when timer
824                                   (cancel-timer timer)
825                                   (setq timer nil))
826                                 (setq response-string
827                                       (concat response-string string))))
828           (set-process-sentinel proc
829                                 (lambda (proc event)
830                                   (condition-case the-error
831                                       (cond
832                                        ((string-prefix-p "open" event)    ; request URL
833                                         (let ((inhibit-eol-conversion t))
834                                           (process-send-string
835                                            proc
836                                            (concat (elpher-address-to-url address)
837                                                    "\r\n"))))
838                                        ((string-prefix-p "deleted" event)) ; do nothing
839                                        ((and (string-empty-p response-string)
840                                              (not force-ipv4))
841                                         ; Try again with IPv4
842                                         (message "Connection failed. Retrying with IPv4.")
843                                         (cancel-timer timer)
844                                         (elpher-get-gemini-response address renderer t))
845                                        (t
846                                         (funcall #'elpher-process-gemini-response
847                                                  response-string
848                                                  renderer)
849                                         (elpher-restore-pos)))
850                                     (error
851                                            (elpher-network-error address the-error))))))
852       (error
853        (error "Error initiating connection to server")))))
854
855 (defun elpher-parse-gemini-response (response)
856   "Parse the RESPONSE string and return a list of components.
857 The list is of the form (code meta body).  A response of nil implies
858 that the response was malformed."
859   (let ((header-end-idx (string-match "\r\n" response)))
860     (if header-end-idx
861         (let ((header (string-trim (substring response 0 header-end-idx)))
862               (body (substring response (+ header-end-idx 2))))
863           (if (>= (length header) 2)
864               (let ((code (substring header 0 2))
865                     (meta (string-trim (substring header 2))))
866                 (list code meta body))
867             (error "Malformed response: No response status found in header %s" header)))
868       (error "Malformed response: No CRLF-delimited header found"))))
869
870 (defun elpher-process-gemini-response (response-string renderer)
871   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
872   (let ((response-components (elpher-parse-gemini-response response-string)))
873     (let ((response-code (elt response-components 0))
874           (response-meta (elt response-components 1))
875           (response-body (elt response-components 2)))
876       (pcase (elt response-code 0)
877         (?1 ; Input required
878          (elpher-with-clean-buffer
879           (insert "Gemini server is requesting input."))
880          (let* ((query-string (read-string (concat response-meta ": ")))
881                 (url (elpher-address-to-url (elpher-page-address elpher-current-page)))
882                 (query-address (elpher-address-from-url (concat url "?" query-string))))
883            (elpher-get-gemini-response query-address renderer)))
884         (?2 ; Normal response
885          (funcall renderer response-body response-meta))
886         (?3 ; Redirect
887          (message "Following redirect to %s" response-meta)
888          (if (>= (length elpher-gemini-redirect-chain) 5)
889              (error "More than 5 consecutive redirects followed"))
890          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
891            (if (member redirect-address elpher-gemini-redirect-chain)
892                (error "Redirect loop detected"))
893            (if (not (string= (elpher-address-protocol redirect-address)
894                              "gemini"))
895                (error "Server tried to automatically redirect to non-gemini URL: %s"
896                       response-meta))
897            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
898            (elpher-get-gemini-response redirect-address renderer)))
899         (?4 ; Temporary failure
900          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
901                 response-code response-meta))
902         (?5 ; Permanent failure
903          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
904                 response-code response-meta))
905         (?6 ; Client certificate required
906          (error "Gemini server requires client certificate (unsupported at this time)"))
907         (_other
908          (error "Gemini server response unknown: %s %s"
909                 response-code response-meta))))))
910
911 (defun elpher-get-gemini-page (renderer)
912   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
913   (let* ((address (elpher-page-address elpher-current-page))
914          (content (elpher-get-cached-content address)))
915     (condition-case the-error
916         (if (and content (funcall renderer nil))
917             (elpher-with-clean-buffer
918               (insert content)
919               (elpher-restore-pos))
920           (elpher-with-clean-buffer
921            (insert "LOADING GEMINI... (use 'u' to cancel)"))
922           (setq elpher-gemini-redirect-chain nil)
923           (elpher-get-gemini-response address renderer))
924       (error
925        (elpher-network-error address the-error)))))
926
927
928 (defun elpher-render-gemini (body &optional mime-type-string)
929   "Render gemini response BODY with rendering MIME-TYPE-STRING."
930   (if (not body)
931       t
932     (let* ((mime-type-string* (if (or (not mime-type-string)
933                                       (string-empty-p mime-type-string))
934                                   "text/gemini; charset=utf-8"
935                                 mime-type-string))
936            (mime-type-split (split-string mime-type-string* ";" t))
937            (mime-type (string-trim (car mime-type-split)))
938            (parameters (mapcar (lambda (s)
939                                  (let ((key-val (split-string s "=")))
940                                    (list (downcase (string-trim (car key-val)))
941                                          (downcase (string-trim (cadr key-val))))))
942                                (cdr mime-type-split))))
943       (when (string-prefix-p "text/" mime-type)
944         (setq body (decode-coding-string
945                     body
946                     (if (assoc "charset" parameters)
947                         (intern (cadr (assoc "charset" parameters)))
948                       'utf-8)))
949         (setq body (replace-regexp-in-string "\r" "" body)))
950       (pcase mime-type
951         ((or "text/gemini" "")
952          (elpher-render-gemini-map body parameters))
953         ("text/html"
954          (elpher-render-html body))
955         ((pred (string-prefix-p "text/"))
956          (elpher-render-gemini-plain-text body parameters))
957         ((pred (string-prefix-p "image/"))
958          (elpher-render-image body))
959         (_other
960          (error "Unsupported MIME type %S" mime-type))))))
961
962 (defun elpher-gemini-get-link-url (line)
963   "Extract the url portion of LINE, a gemini map file link line."
964   (string-trim (elt (split-string (substring line 2)) 0)))
965
966 (defun elpher-gemini-get-link-display-string (line)
967   "Extract the display string portion of LINE, a gemini map file link line."
968   (let* ((rest (string-trim (elt (split-string line "=>") 1)))
969          (idx (string-match "[ \t]" rest)))
970     (if idx
971         (string-trim (substring rest (+ idx 1)))
972       "")))
973
974 (defun elpher-collapse-dot-sequences (filename)
975   "Collapse dot sequences in FILENAME.
976 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
977   (let* ((path (split-string filename "/"))
978          (path-reversed-normalized
979           (seq-reduce (lambda (a b)
980                         (cond ((and a (equal b "..") (cdr a)))
981                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
982                               ((equal b ".") a)
983                               (t (cons b a))))
984                       path nil)))
985     (string-join (reverse path-reversed-normalized) "/")))
986
987 (defun elpher-address-from-gemini-url (url)
988   "Extract address from URL with defaults as per gemini map files."
989   (let ((address (url-generic-parse-url url)))
990     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
991       (setf (url-fullness address) t)
992       (if (url-host address) ;if there is an explicit host, filenames are absolute
993           (if (string-empty-p (url-filename address))
994               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
995         (setf (url-host address) (url-host (elpher-page-address elpher-current-page)))
996         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
997           (setf (url-filename address)
998                 (concat (file-name-directory
999                          (url-filename (elpher-page-address elpher-current-page)))
1000                         (url-filename address)))))
1001       (unless (url-type address)
1002         (setf (url-type address) "gemini"))
1003       (if (equal (url-type address) "gemini")
1004           (setf (url-filename address)
1005                 (elpher-collapse-dot-sequences (url-filename address)))))
1006     address))
1007
1008 (defun elpher-render-gemini-map (data _parameters)
1009   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1010   (elpher-with-clean-buffer
1011    (dolist (line (split-string data "\n"))
1012      (if (string-prefix-p "=>" line)
1013          (let* ((url (elpher-gemini-get-link-url line))
1014                 (display-string (elpher-gemini-get-link-display-string line))
1015                 (address (elpher-address-from-gemini-url url)))
1016            (if (> (length display-string) 0)
1017                (elpher-insert-index-record display-string address)
1018              (elpher-insert-index-record url address)))
1019        (elpher-insert-index-record line)))
1020    (elpher-cache-content
1021     (elpher-page-address elpher-current-page)
1022     (buffer-string))))
1023
1024 (defun elpher-render-gemini-plain-text (data _parameters)
1025   "Render DATA as plain text file.  PARAMETERS is currently unused."
1026   (elpher-with-clean-buffer
1027    (insert (elpher-process-text-for-display data))
1028    (elpher-cache-content
1029     (elpher-page-address elpher-current-page)
1030     (buffer-string))))
1031
1032 ;; Other URL page opening
1033
1034 (defun elpher-get-other-url-page (renderer)
1035   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1036   (when renderer
1037     (elpher-visit-previous-page)
1038     (error "Command not supported for general URLs"))
1039   (let* ((address (elpher-page-address elpher-current-page))
1040          (url (elpher-address-to-url address)))
1041     (progn
1042       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1043       (message "Opening URL...")
1044       (if elpher-open-urls-with-eww
1045           (browse-web url)
1046         (browse-url url)))))
1047
1048 ;; Telnet page connection
1049
1050 (defun elpher-get-telnet-page (renderer)
1051   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1052   (when renderer
1053     (elpher-visit-previous-page)
1054     (error "Command not supported for telnet URLs"))
1055   (let* ((address (elpher-page-address elpher-current-page))
1056          (host (elpher-address-host address))
1057          (port (elpher-address-port address)))
1058     (elpher-visit-previous-page)
1059     (if (> port 0)
1060         (telnet host port)
1061       (telnet host))))
1062
1063 ;; Start page page retrieval
1064
1065 (defun elpher-get-start-page (renderer)
1066   "Getter which displays the start page (RENDERER must be nil)."
1067   (when renderer
1068     (elpher-visit-previous-page)
1069     (error "Command not supported for start page"))
1070   (elpher-with-clean-buffer
1071    (insert "     --------------------------------------------\n"
1072            "                Elpher Gopher Client             \n"
1073            "                   version " elpher-version "\n"
1074            "     --------------------------------------------\n"
1075            "\n"
1076            "Default bindings:\n"
1077            "\n"
1078            " - TAB/Shift-TAB: next/prev item on current page\n"
1079            " - RET/mouse-1: open item under cursor\n"
1080            " - m: select an item on current page by name (autocompletes)\n"
1081            " - u/mouse-3: return to previous page\n"
1082            " - o/O: visit different selector or the root menu of the current server\n"
1083            " - g: go to a particular gopher address\n"
1084            " - d/D: download item under cursor or current page\n"
1085            " - i/I: info on item under cursor or current page\n"
1086            " - c/C: copy URL representation of item under cursor or current page\n"
1087            " - a/A: bookmark the item under cursor or current page\n"
1088            " - x/X: remove bookmark for item under cursor or current page\n"
1089            " - B: visit the bookmarks page\n"
1090            " - r: redraw current page (using cached contents if available)\n"
1091            " - R: reload current page (regenerates cache)\n"
1092            " - S: set character coding system for gopher (default is to autodetect)\n"
1093            " - T: toggle TLS gopher mode\n"
1094            " - .: display the raw server response for the current page\n"
1095            "\n"
1096            "Start your exploration of gopher space:\n")
1097    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1098                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1099    (insert "\n"
1100            "Alternatively, select the following item and enter some search terms:\n")
1101    (elpher-insert-index-record "Veronica-2 Gopher Search Engine"
1102                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1103    (insert "\n"
1104            "This page contains your bookmarked sites (also visit with B):\n")
1105    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1106    (insert "\n"
1107            "For Elpher release news or to leave feedback, visit:\n")
1108    (elpher-insert-index-record "The Elpher Project Page"
1109                                (elpher-make-gopher-address ?1
1110                                                            "/projects/elpher/"
1111                                                            "thelambdalab.xyz"
1112                                                            70))
1113    (insert "\n"
1114            "** Refer to the ")
1115    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1116      (insert-text-button "Elpher info manual"
1117                          'face 'link
1118                          'action (lambda (_)
1119                                    (interactive)
1120                                    (info "(elpher)"))
1121                          'follow-link t
1122                          'help-echo help-string))
1123    (insert " for the full documentation. **\n")
1124    (insert (propertize
1125             (concat "  (This should be available if you have installed Elpher using\n"
1126                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1127             'face 'shadow))
1128    (elpher-restore-pos)))
1129
1130 ;; Bookmarks page page retrieval
1131
1132 (defun elpher-get-bookmarks-page (renderer)
1133   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1134   (when renderer
1135     (elpher-visit-previous-page)
1136     (error "Command not supported for bookmarks page"))
1137   (elpher-with-clean-buffer
1138    (insert "---- Bookmark list ----\n\n")
1139    (let ((bookmarks (elpher-load-bookmarks)))
1140      (if bookmarks
1141          (dolist (bookmark bookmarks)
1142            (let ((display-string (elpher-bookmark-display-string bookmark))
1143                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1144              (elpher-insert-index-record display-string address)))
1145        (insert "No bookmarks found.\n")))
1146    (insert "\n-----------------------\n"
1147            "\n"
1148            "- u: return to previous page\n"
1149            "- x: delete selected bookmark\n"
1150            "- a: rename selected bookmark\n"
1151            "\n"
1152            "Bookmarks are stored in the file ")
1153    (let ((filename (locate-user-emacs-file "elpher-bookmarks"))
1154          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1155      (insert-text-button filename
1156                          'face 'link
1157                          'action (lambda (_)
1158                                    (interactive)
1159                                    (find-file filename))
1160                          'follow-link t
1161                          'help-echo help-string))
1162    (insert "\n")
1163    (elpher-restore-pos)))
1164   
1165
1166 ;;; Bookmarks
1167 ;;
1168
1169 (defun elpher-make-bookmark (display-string url)
1170   "Make an elpher bookmark.
1171 DISPLAY-STRING determines how the bookmark will appear in the
1172 bookmark list, while URL is the url of the entry."
1173   (list display-string url))
1174   
1175 (defun elpher-bookmark-display-string (bookmark)
1176   "Get the display string of BOOKMARK."
1177   (elt bookmark 0))
1178
1179 (defun elpher-set-bookmark-display-string (bookmark display-string)
1180   "Set the display string of BOOKMARK to DISPLAY-STRING."
1181   (setcar bookmark display-string))
1182
1183 (defun elpher-bookmark-url (bookmark)
1184   "Get the address for BOOKMARK."
1185   (elt bookmark 1))
1186
1187 (defun elpher-save-bookmarks (bookmarks)
1188   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1189 Beware that this completely replaces the existing contents of the file."
1190   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
1191     (erase-buffer)
1192     (insert "; Elpher bookmarks file\n\n"
1193             "; Bookmarks are stored as a list of (label URL) items.\n"
1194             "; Feel free to edit by hand, but take care to ensure\n"
1195             "; the list structure remains intact.\n\n")
1196     (pp bookmarks (current-buffer))))
1197
1198 (defun elpher-load-bookmarks ()
1199   "Get the list of bookmarks from the users's bookmark file."
1200   (let ((bookmarks
1201          (with-temp-buffer
1202            (ignore-errors
1203              (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
1204              (goto-char (point-min))
1205              (read (current-buffer))))))
1206     (if (and bookmarks (listp (cadar bookmarks)))
1207         (progn
1208           (message "Reading old bookmark file. (Will be updated on write.)")
1209           (mapcar (lambda (old-bm)
1210                     (list (car old-bm)
1211                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1212                                                         (cadr old-bm)))))
1213                   bookmarks))
1214       bookmarks)))
1215
1216 (defun elpher-add-address-bookmark (address display-string)
1217   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1218 If ADDRESS is already bookmarked, update the label only."
1219   (let ((bookmarks (elpher-load-bookmarks))
1220         (url (elpher-address-to-url address)))
1221     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1222       (if existing-bookmark
1223           (elpher-set-bookmark-display-string existing-bookmark display-string)
1224         (push (elpher-make-bookmark display-string url) bookmarks)))
1225     (elpher-save-bookmarks bookmarks)))
1226
1227 (defun elpher-remove-address-bookmark (address)
1228   "Remove any bookmark to ADDRESS."
1229   (let ((url (elpher-address-to-url address)))
1230     (elpher-save-bookmarks
1231      (seq-filter (lambda (bookmark)
1232                    (not (equal (elpher-bookmark-url bookmark) url)))
1233                  (elpher-load-bookmarks)))))
1234
1235 ;;; Interactive procedures
1236 ;;
1237
1238 (defun elpher-next-link ()
1239   "Move point to the next link on the current page."
1240   (interactive)
1241   (forward-button 1))
1242
1243 (defun elpher-prev-link ()
1244   "Move point to the previous link on the current page."
1245   (interactive)
1246   (backward-button 1))
1247
1248 (defun elpher-follow-current-link ()
1249   "Open the link or url at point."
1250   (interactive)
1251   (push-button))
1252
1253 (defun elpher-go (host-or-url)
1254   "Go to a particular gopher site HOST-OR-URL.
1255 When run interactively HOST-OR-URL is read from the minibuffer."
1256   (interactive "sGopher or Gemini URL: ")
1257   (let ((page (elpher-make-page host-or-url
1258                                 (elpher-address-from-url host-or-url))))
1259     (switch-to-buffer "*elpher*")
1260     (elpher-visit-page page)
1261     '()))
1262
1263 (defun elpher-go-current ()
1264   "Go to a particular site read from the minibuffer, initialized with the current URL."
1265   (interactive)
1266   (let ((address (elpher-page-address elpher-current-page)))
1267     (if (elpher-address-special-p address)
1268         (error "Command invalid for this page")
1269       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1270         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1271
1272 (defun elpher-redraw ()
1273   "Redraw current page."
1274   (interactive)
1275   (elpher-visit-page elpher-current-page))
1276
1277 (defun elpher-reload ()
1278   "Reload current page."
1279   (interactive)
1280   (elpher-reload-current-page))
1281
1282 (defun elpher-toggle-tls ()
1283   "Toggle TLS encryption mode for gopher."
1284   (interactive)
1285   (setq elpher-use-tls (not elpher-use-tls))
1286   (if elpher-use-tls
1287       (if (gnutls-available-p)
1288           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1289         (setq elpher-use-tls nil)
1290         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1291     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1292
1293 (defun elpher-view-raw ()
1294   "View raw server response for current page."
1295   (interactive)
1296   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1297       (error "This page was not generated by a server")
1298     (elpher-visit-page elpher-current-page
1299                        #'elpher-render-raw)))
1300
1301 (defun elpher-back ()
1302   "Go to previous site."
1303   (interactive)
1304   (elpher-visit-previous-page))
1305
1306 (defun elpher-download ()
1307   "Download the link at point."
1308   (interactive)
1309   (let ((button (button-at (point))))
1310     (if button
1311         (let ((page (button-get button 'elpher-page)))
1312           (if (elpher-address-special-p (elpher-page-address page))
1313               (error "Cannot download %s"
1314                      (elpher-page-display-string page))
1315             (elpher-visit-page (button-get button 'elpher-page)
1316                                #'elpher-render-download)))
1317       (error "No link selected"))))
1318
1319 (defun elpher-download-current ()
1320   "Download the current page."
1321   (interactive)
1322   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1323       (error "Cannot download %s"
1324              (elpher-page-display-string elpher-current-page))
1325     (elpher-visit-page (elpher-make-page
1326                         (elpher-page-display-string elpher-current-page)
1327                         (elpher-page-address elpher-current-page))
1328                        #'elpher-render-download
1329                        t)))
1330
1331 (defun elpher-build-link-map ()
1332   "Build alist mapping link names to destination pages in current buffer."
1333   (let ((link-map nil)
1334         (b (next-button (point-min) t)))
1335     (while b
1336       (push (cons (button-label b) b) link-map)
1337       (setq b (next-button (button-start b))))
1338     link-map))
1339
1340 (defun elpher-jump ()
1341   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1342   (interactive)
1343   (let* ((link-map (elpher-build-link-map)))
1344     (if link-map
1345         (let ((key (let ((completion-ignore-case t))
1346                      (completing-read "Directory item/link: "
1347                                       link-map nil t))))
1348           (if (and key (> (length key) 0))
1349               (let ((b (cdr (assoc key link-map))))
1350                 (goto-char (button-start b))
1351                 (button-activate b)))))))
1352
1353 (defun elpher-root-dir ()
1354   "Visit root of current server."
1355   (interactive)
1356   (let ((address (elpher-page-address elpher-current-page)))
1357     (if (not (elpher-address-special-p address))
1358         (if (or (member (url-filename address) '("/" ""))
1359                 (and (elpher-address-gopher-p address)
1360                      (= (length (elpher-gopher-address-selector address)) 0)))
1361             (error "Already at root directory of current server")
1362           (let ((address-copy (elpher-address-from-url
1363                                (elpher-address-to-url address))))
1364             (setf (url-filename address-copy) "")
1365             (elpher-visit-page
1366              (elpher-make-page (elpher-address-to-url address-copy)
1367                                address-copy))))
1368       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1369
1370 (defun elpher-bookmarks-current-p ()
1371   "Return non-nil if current page is a bookmarks page."
1372   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1373          '(special bookmarks)))
1374
1375 (defun elpher-reload-bookmarks ()
1376   "Reload bookmarks if current page is a bookmarks page."
1377   (if (elpher-bookmarks-current-p)
1378       (elpher-reload-current-page)))
1379
1380 (defun elpher-bookmark-current ()
1381   "Bookmark the current page."
1382   (interactive)
1383   (let ((address (elpher-page-address elpher-current-page))
1384         (display-string (elpher-page-display-string elpher-current-page)))
1385     (if (not (elpher-address-special-p address))
1386         (let ((bookmark-display-string (read-string "Bookmark display string: "
1387                                                     display-string)))
1388           (elpher-add-address-bookmark address bookmark-display-string)
1389           (message "Bookmark added."))
1390       (error "Cannot bookmark %s" display-string))))
1391
1392 (defun elpher-bookmark-link ()
1393   "Bookmark the link at point."
1394   (interactive)
1395   (let ((button (button-at (point))))
1396     (if button
1397         (let* ((page (button-get button 'elpher-page))
1398                (address (elpher-page-address page))
1399                (display-string (elpher-page-display-string page)))
1400           (if (not (elpher-address-special-p address))
1401               (let ((bookmark-display-string (read-string "Bookmark display string: "
1402                                                           display-string)))
1403                 (elpher-add-address-bookmark address bookmark-display-string)
1404                 (elpher-reload-bookmarks)
1405                 (message "Bookmark added."))
1406             (error "Cannot bookmark %s" display-string)))
1407       (error "No link selected"))))
1408
1409 (defun elpher-unbookmark-current ()
1410   "Remove bookmark for the current page."
1411   (interactive)
1412   (let ((address (elpher-page-address elpher-current-page)))
1413     (unless (elpher-address-special-p address)
1414       (elpher-remove-address-bookmark address)
1415       (message "Bookmark removed."))))
1416
1417 (defun elpher-unbookmark-link ()
1418   "Remove bookmark for the link at point."
1419   (interactive)
1420   (let ((button (button-at (point))))
1421     (if button
1422         (let ((page (button-get button 'elpher-page)))
1423           (elpher-remove-address-bookmark (elpher-page-address page))
1424           (elpher-reload-bookmarks)
1425           (message "Bookmark removed."))
1426       (error "No link selected"))))
1427
1428 (defun elpher-bookmarks ()
1429   "Visit bookmarks page."
1430   (interactive)
1431   (switch-to-buffer "*elpher*")
1432   (elpher-visit-page
1433    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1434
1435 (defun elpher-info-page (page)
1436   "Display information on PAGE."
1437   (let ((display-string (elpher-page-display-string page))
1438         (address (elpher-page-address page)))
1439     (if (elpher-address-special-p address)
1440         (message "Special page: %s" display-string)
1441       (message "%s" (elpher-address-to-url address)))))
1442
1443 (defun elpher-info-link ()
1444   "Display information on page corresponding to link at point."
1445   (interactive)
1446   (let ((button (button-at (point))))
1447     (if button
1448         (elpher-info-page (button-get button 'elpher-page))
1449       (error "No item selected"))))
1450   
1451 (defun elpher-info-current ()
1452   "Display information on current page."
1453   (interactive)
1454   (elpher-info-page elpher-current-page))
1455
1456 (defun elpher-copy-page-url (page)
1457   "Copy URL representation of address of PAGE to `kill-ring'."
1458   (let ((address (elpher-page-address page)))
1459     (if (elpher-address-special-p address)
1460         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1461       (let ((url (elpher-address-to-url address)))
1462         (message "Copied \"%s\" to kill-ring/clipboard." url)
1463         (kill-new url)))))
1464
1465 (defun elpher-copy-link-url ()
1466   "Copy URL of item at point to `kill-ring'."
1467   (interactive)
1468   (let ((button (button-at (point))))
1469     (if button
1470         (elpher-copy-page-url (button-get button 'elpher-page))
1471       (error "No item selected"))))
1472
1473 (defun elpher-copy-current-url ()
1474   "Copy URL of current page to `kill-ring'."
1475   (interactive)
1476   (elpher-copy-page-url elpher-current-page))
1477
1478 (defun elpher-set-gopher-coding-system ()
1479   "Specify an explicit character coding system for gopher selectors."
1480   (interactive)
1481   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1482     (setq elpher-user-coding-system system)
1483     (if system
1484         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1485       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1486
1487
1488 ;;; Mode and keymap
1489 ;;
1490
1491 (defvar elpher-mode-map
1492   (let ((map (make-sparse-keymap)))
1493     (define-key map (kbd "TAB") 'elpher-next-link)
1494     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1495     (define-key map (kbd "u") 'elpher-back)
1496     (define-key map [mouse-3] 'elpher-back)
1497     (define-key map (kbd "O") 'elpher-root-dir)
1498     (define-key map (kbd "g") 'elpher-go)
1499     (define-key map (kbd "o") 'elpher-go-current)
1500     (define-key map (kbd "r") 'elpher-redraw)
1501     (define-key map (kbd "R") 'elpher-reload)
1502     (define-key map (kbd "T") 'elpher-toggle-tls)
1503     (define-key map (kbd ".") 'elpher-view-raw)
1504     (define-key map (kbd "d") 'elpher-download)
1505     (define-key map (kbd "D") 'elpher-download-current)
1506     (define-key map (kbd "m") 'elpher-jump)
1507     (define-key map (kbd "i") 'elpher-info-link)
1508     (define-key map (kbd "I") 'elpher-info-current)
1509     (define-key map (kbd "c") 'elpher-copy-link-url)
1510     (define-key map (kbd "C") 'elpher-copy-current-url)
1511     (define-key map (kbd "a") 'elpher-bookmark-link)
1512     (define-key map (kbd "A") 'elpher-bookmark-current)
1513     (define-key map (kbd "x") 'elpher-unbookmark-link)
1514     (define-key map (kbd "X") 'elpher-unbookmark-current)
1515     (define-key map (kbd "B") 'elpher-bookmarks)
1516     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1517     (when (fboundp 'evil-define-key*)
1518       (evil-define-key* 'motion map
1519         (kbd "TAB") 'elpher-next-link
1520         (kbd "C-") 'elpher-follow-current-link
1521         (kbd "C-t") 'elpher-back
1522         (kbd "u") 'elpher-back
1523         [mouse-3] 'elpher-back
1524         (kbd "g") 'elpher-go
1525         (kbd "o") 'elpher-go-current
1526         (kbd "r") 'elpher-redraw
1527         (kbd "R") 'elpher-reload
1528         (kbd "T") 'elpher-toggle-tls
1529         (kbd ".") 'elpher-view-raw
1530         (kbd "d") 'elpher-download
1531         (kbd "D") 'elpher-download-current
1532         (kbd "m") 'elpher-jump
1533         (kbd "i") 'elpher-info-link
1534         (kbd "I") 'elpher-info-current
1535         (kbd "c") 'elpher-copy-link-url
1536         (kbd "C") 'elpher-copy-current-url
1537         (kbd "a") 'elpher-bookmark-link
1538         (kbd "A") 'elpher-bookmark-current
1539         (kbd "x") 'elpher-unbookmark-link
1540         (kbd "X") 'elpher-unbookmark-current
1541         (kbd "B") 'elpher-bookmarks
1542         (kbd "S") 'elpher-set-gopher-coding-system))
1543     map)
1544   "Keymap for gopher client.")
1545
1546 (define-derived-mode elpher-mode special-mode "elpher"
1547   "Major mode for elpher, an elisp gopher client.
1548
1549 This mode is automatically enabled by the interactive
1550 functions which initialize the gopher client, namely
1551 `elpher', `elpher-go' and `elpher-bookmarks'.")
1552
1553 (when (fboundp 'evil-set-initial-state)
1554   (evil-set-initial-state 'elpher-mode 'motion))
1555
1556
1557 ;;; Main start procedure
1558 ;;
1559
1560 ;;;###autoload
1561 (defun elpher ()
1562   "Start elpher with default landing page."
1563   (interactive)
1564   (if (get-buffer "*elpher*")
1565       (switch-to-buffer "*elpher*")
1566     (switch-to-buffer "*elpher*")
1567     (setq elpher-current-page nil)
1568     (let ((start-page (elpher-make-page "Elpher Start Page"
1569                                         (elpher-make-special-address 'start))))
1570       (elpher-visit-page start-page)))
1571   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1572
1573 ;;; elpher.el ends here