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