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