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