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