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