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