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