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