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