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