1 ;;; elpher.el --- A friendly gopher and gemini client -*- lexical-binding: t -*-
3 ;; Copyright (C) 2021 Jens Östlund <jostlund@gmail.com>
4 ;; Copyright (C) 2021 F. Jason Park <jp@neverwas.me>
5 ;; Copyright (C) 2021 Christopher Brannon <chris@the-brannons.com>
6 ;; Copyright (C) 2021 Omar Polo <op@omarpolo.com>
7 ;; Copyright (C) 2021 Noodles! <nnoodle@chiru.no>
8 ;; Copyright (C) 2020-2021 Alex Schroeder <alex@gnu.org>
9 ;; Copyright (C) 2020 Zhiwei Chen <chenzhiwei03@kuaishou.com>
10 ;; Copyright (C) 2020 condy0919 <condy0919@gmail.com>
11 ;; Copyright (C) 2020 Alexis <flexibeast@gmail.com>
12 ;; Copyright (C) 2020 Étienne Deparis <etienne@depar.is>
13 ;; Copyright (C) 2020 Simon Nicolussi <sinic@sinic.name>
14 ;; Copyright (C) 2020 Michel Alexandre Salim <michel@michel-slm.name>
15 ;; Copyright (C) 2020 Koushk Roy <kroy@twilio.com>
16 ;; Copyright (C) 2020 Vee <vee@vnsf.xyz>
17 ;; Copyright (C) 2020 Simon South <simon@simonsouth.net>
18 ;; Copyright (C) 2019-2020 Tim Vaughan <plugd@thelambdalab.xyz>
20 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
21 ;; Created: 11 April 2019
23 ;; Keywords: comm gopher
24 ;; Homepage: https://alexschroeder.ch/cgit/elpher
25 ;; Package-Requires: ((emacs "27.1"))
27 ;; This file is not part of GNU Emacs.
29 ;; This program is free software: you can redistribute it and/or modify
30 ;; it under the terms of the GNU General Public License as published by
31 ;; the Free Software Foundation, either version 3 of the License, or
32 ;; (at your option) any later version.
34 ;; This program is distributed in the hope that it will be useful,
35 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
36 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 ;; GNU General Public License for more details.
39 ;; You should have received a copy of the GNU General Public License
40 ;; along with this file. If not, see <http://www.gnu.org/licenses/>.
44 ;; Elpher aims to provide a practical and friendly gopher and gemini
45 ;; client for GNU Emacs. It supports:
47 ;; - intuitive keyboard and mouse-driven browsing,
48 ;; - out-of-the-box compatibility with evil-mode,
49 ;; - clickable web and gopher links *in plain text*,
50 ;; - caching of visited sites,
51 ;; - pleasant and configurable colouring of Gopher directories,
52 ;; - direct visualisation of image files,
53 ;; - a simple bookmark management system,
54 ;; - gopher connections using TLS encryption,
55 ;; - the fledgling Gemini protocol,
56 ;; - the greybeard Finger protocol.
58 ;; To launch Elpher, simply use 'M-x elpher'. This will open a start
59 ;; page containing information on key bindings and suggested starting
60 ;; points for your gopher exploration.
62 ;; Full instructions can be found in the Elpher info manual.
64 ;; Elpher is under active development. Any suggestions for
65 ;; improvements are welcome, and can be made on the official
66 ;; project page, https://alexschroeder.ch/cgit/elpher.
85 ;;; ANSI colors or XTerm colors
87 (or (require 'xterm-color nil t)
88 (require 'ansi-color))
90 (defalias 'elpher-color-filter-apply
91 (if (fboundp 'xterm-color-filter)
93 (let ((xterm-color-render nil))
94 (xterm-color-filter s)))
95 'ansi-color-filter-apply)
96 "A function to filter out ANSI escape sequences.")
97 (defalias 'elpher-color-apply
98 (if (fboundp 'xterm-color-filter)
101 "A function to apply ANSI escape sequences.")
106 (defconst elpher-version "2.11.0"
107 "Current version of elpher.")
109 (defconst elpher-margin-width 6
110 "Width of left-hand margin used when rendering indicies.")
112 (defconst elpher-type-map
113 '(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
114 ((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
115 ((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
116 ((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
117 ((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
118 ((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
119 ((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
120 ((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
121 ((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
122 ((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
123 ((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
124 ((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
125 ((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
126 (gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
127 (finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
128 (telnet elpher-get-telnet-page nil "tel" elpher-telnet)
129 (other-url elpher-get-other-url-page nil "url" elpher-other-url)
130 ((special bookmarks) elpher-get-bookmarks-page nil "/" elpher-index)
131 ((special start) elpher-get-start-page nil))
132 "Association list from types to getters, renderers, margin codes and index faces.")
135 ;;; Internal variables
139 (defvar elpher--gemini-page-headings nil
140 "List of headings on the page.")
142 (defvar elpher--gemini-page-links nil
143 "List of links on the page.")
145 (defvar elpher--gemini-page-links-cache (make-hash-table :test 'equal)
146 "Hash of addresses and page links.")
148 ;;; Customization group
152 "A gopher and gemini client."
153 :group 'applications)
155 ;; General appearance and customizations
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."
162 (defcustom elpher-use-header t
163 "If non-nil, display current page information in buffer header."
166 (defcustom elpher-auto-disengage-TLS nil
167 "If non-nil, automatically disengage TLS following an unsuccessful connection.
168 While enabling this may seem convenient, it is also potentially
169 dangerous as it allows switching from an encrypted channel back to
170 plain text without user input."
173 (defcustom elpher-connection-timeout 5
174 "Specifies the number of seconds to wait for a network connection to time out."
177 (defcustom elpher-filter-ansi-from-text nil
178 "If non-nil, filter ANSI escape sequences from text.
179 The default behaviour is to use the ansi-color package to interpret these
183 (defcustom elpher-certificate-directory
184 (file-name-as-directory (locate-user-emacs-file "elpher-certificates"))
185 "Specify the name of the directory where client certificates will be stored.
186 These certificates may be used for establishing authenticated TLS connections."
189 (defcustom elpher-openssl-command "openssl"
190 "The command used to launch openssl when generating TLS client certificates."
193 (defcustom elpher-default-url-type "gopher"
194 "Default URL type (i.e. scheme) to assume if not explicitly given."
195 :type '(choice (const "gopher")
198 (defcustom elpher-gemini-TLS-cert-checks nil
199 "If non-nil, verify gemini server TLS certs using the default security level.
200 Otherwise, certificate verification is disabled.
202 This defaults to off because it is standard practice for Gemini servers
203 to use self-signed certificates, meaning that most servers provide what
204 EMACS considers to be an invalid certificate."
207 (defcustom elpher-gemini-max-fill-width 80
208 "Specify the maximum default width (in columns) of text/gemini documents.
209 The actual width used is the minimum of this value and the window width at
210 the time when the text is rendered."
213 (defcustom elpher-gemini-link-string "→ "
214 "Specify the string used to indicate links when rendering gemini maps.
218 (defcustom elpher-gemini-bullet-string "•"
219 "Specify the string used for bullets when rendering gemini maps."
222 (defcustom elpher-bookmarks-file (locate-user-emacs-file "elpher-bookmarks")
223 "Specify the name of the file where elpher bookmarks will be saved."
226 (defcustom elpher-ipv4-always nil
227 "If non-nil, elpher will always use IPv4 to establish network connections.
228 This can be useful when browsing from a computer that supports IPv6, because
229 some servers which do not support IPv6 can take a long time to time-out."
232 (defcustom elpher-socks-always nil
233 "If non-nil, elpher will establish network connections over a SOCKS proxy.
234 Otherwise, the SOCKS proxy is only used for connections to onion services."
237 (defcustom elpher-gemini-number-links nil
238 "If non-nil, number links in gemini pages when rendering.
239 Links can be accessed by pressing `v' ('visit') followed by the link number."
242 ;; Face customizations
244 (defgroup elpher-faces nil
245 "Elpher face customizations."
248 (defface elpher-index
249 '((t :inherit font-lock-keyword-face))
250 "Face used for directory type directory records.")
254 "Face used for text type directory records.")
257 '((t :inherit default))
258 "Face used for info type directory records.")
260 (defface elpher-image
261 '((t :inherit font-lock-string-face))
262 "Face used for image type directory records.")
264 (defface elpher-search
265 '((t :inherit warning))
266 "Face used for search type directory records.")
269 '((t :inherit font-lock-comment-face))
270 "Face used for html type directory records.")
272 (defface elpher-gemini
273 '((t :inherit font-lock-constant-face))
274 "Face used for Gemini type directory records.")
276 (defface elpher-other-url
277 '((t :inherit font-lock-comment-face))
278 "Face used for other URL type links records.")
280 (defface elpher-telnet
281 '((t :inherit font-lock-function-name-face))
282 "Face used for telnet type directory records.")
284 (defface elpher-binary
285 '((t :inherit font-lock-doc-face))
286 "Face used for binary type directory records.")
288 (defface elpher-unknown
289 '((t :inherit error))
290 "Face used for directory records with unknown/unsupported types.")
292 (defface elpher-margin-key
294 "Face used for directory margin key.")
296 (defface elpher-margin-brackets
297 '((t :inherit shadow))
298 "Face used for brackets around directory margin key.")
300 (defface elpher-gemini-heading1
301 '((t :inherit bold :height 1.8))
302 "Face used for gemini heading level 1.")
304 (defface elpher-gemini-heading2
305 '((t :inherit bold :height 1.5))
306 "Face used for gemini heading level 2.")
308 (defface elpher-gemini-heading3
309 '((t :inherit bold :height 1.2))
310 "Face used for gemini heading level 3.")
312 (defface elpher-gemini-preformatted
313 '((t :inherit fixed-pitch))
314 "Face used for pre-formatted gemini text blocks.")
316 (defface elpher-gemini-quoted
317 '((t :inherit font-lock-doc-face))
318 "Face used for gemini quoted texts.")
325 ;; An elpher "address" object is either a url object or a symbol.
326 ;; Symbol addresses are "special", corresponding to pages generated
327 ;; dynamically for and by elpher. All others represent pages which
328 ;; rely on content retrieved over the network.
330 (defun elpher-address-from-url (url-string)
331 "Create a ADDRESS object corresponding to the given URL-STRING."
332 (let ((data (match-data))) ; Prevent parsing clobbering match data
334 (let ((url (url-generic-parse-url url-string)))
335 (unless (and (not (url-fullness url)) (url-type url))
336 (setf (url-fullness url) t)
337 (setf (url-filename url)
338 (url-unhex-string (url-filename url)))
339 (unless (url-type url)
340 (setf (url-type url) elpher-default-url-type))
341 (unless (url-host url)
342 (let ((p (split-string (url-filename url) "/" nil nil)))
343 (setf (url-host url) (car p))
344 (setf (url-filename url)
346 (concat "/" (mapconcat #'identity (cdr p) "/"))
348 (when (or (equal "gopher" (url-type url))
349 (equal "gophers" (url-type url)))
351 (when (or (equal (url-filename url) "")
352 (equal (url-filename url) "/"))
353 (setf (url-filename url) "/1")))
354 (when (equal "gemini" (url-type url))
356 (if (equal (url-filename url) "")
357 (setf (url-filename url) "/"))))
358 (elpher-remove-redundant-ports url))
359 (set-match-data data))))
361 (defun elpher-remove-redundant-ports (address)
362 "Remove redundant port specifiers from ADDRESS.
363 Here 'redundant' means that the specified port matches the default
364 for that protocol, eg 70 for gopher."
365 (if (and (not (elpher-address-special-p address))
366 (eq (url-portspec address) ; (url-port) is too slow!
367 (pcase (url-type address)
369 ((or "gopher" "gophers") 70)
372 (setf (url-portspec address) nil))
375 (defun elpher-make-gopher-address (type selector host port &optional tls)
376 "Create an ADDRESS object using gopher directory record attributes.
377 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
378 If the optional attribute TLS is non-nil, the address will be marked as
379 requiring gopher-over-TLS."
381 ((equal type ?i) nil)
382 ((and (equal type ?h)
383 (string-prefix-p "URL:" selector))
384 (elpher-address-from-url (elt (split-string selector "URL:") 1)))
386 (elpher-address-from-url
389 ":" (number-to-string port))))
391 (elpher-address-from-url
392 (concat "gopher" (if tls "s" "")
394 ":" (number-to-string port)
398 (defun elpher-make-special-address (type)
399 "Create an ADDRESS object corresponding to the given special address symbol TYPE."
402 (defun elpher-make-start-page ()
403 "Create the start page."
404 (elpher-make-page "Elpher Start Page"
405 (elpher-make-special-address 'start)))
407 (defun elpher-address-to-url (address)
408 "Get string representation of ADDRESS, or nil if ADDRESS is special."
409 (if (elpher-address-special-p address)
411 (url-encode-url (url-recreate-url address))))
413 (defun elpher-address-type (address)
414 "Retrieve type of ADDRESS object.
415 This is used to determine how to retrieve and render the document the
416 address refers to, via the table `elpher-type-map'."
417 (if (symbolp address)
418 (list 'special address)
419 (let ((protocol (url-type address)))
420 (cond ((or (equal protocol "gopher")
421 (equal protocol "gophers"))
423 (if (member (url-filename address) '("" "/"))
425 (string-to-char (substring (url-filename address) 1)))))
426 ((equal protocol "gemini")
428 ((equal protocol "telnet")
430 ((equal protocol "finger")
434 (defun elpher-address-protocol (address)
435 "Retrieve the transport protocol for ADDRESS. This is nil for special addresses."
436 (if (symbolp address)
440 (defun elpher-address-filename (address)
441 "Retrieve the filename component of ADDRESS.
442 For gopher addresses this is a combination of the selector type and selector."
443 (if (symbolp address)
445 (url-filename address)))
447 (defun elpher-address-host (address)
448 "Retrieve host from ADDRESS object."
451 (defun elpher-address-user (address)
452 "Retrieve user from ADDRESS object."
455 (defun elpher-address-port (address)
456 "Retrieve port from ADDRESS object.
457 If no address is defined, returns 0. (This is for compatibility with the URL library.)"
458 (if (symbolp address)
462 (defun elpher-address-special-p (address)
463 "Return non-nil if ADDRESS object is special (e.g. start page, bookmarks page)."
466 (defun elpher-address-gopher-p (address)
467 "Return non-nill if ADDRESS object is a gopher address."
468 (and (not (elpher-address-special-p address))
469 (member (elpher-address-protocol address) '("gopher gophers"))))
471 (defun elpher-gopher-address-selector (address)
472 "Retrieve gopher selector from ADDRESS object."
473 (if (member (url-filename address) '("" "/"))
475 (url-unhex-string (substring (url-filename address) 2))))
480 (defvar elpher-content-cache (make-hash-table :test 'equal))
481 (defvar elpher-pos-cache (make-hash-table :test 'equal))
483 (defun elpher-get-cached-content (address)
484 "Retrieve the cached content for ADDRESS, or nil if none exists."
485 (gethash address elpher-content-cache))
487 (defun elpher-cache-content (address content)
488 "Set the content cache for ADDRESS to CONTENT."
489 (puthash address content elpher-content-cache))
491 (defun elpher-get-cached-pos (address)
492 "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
493 (gethash address elpher-pos-cache))
495 (defun elpher-cache-pos (address pos)
496 "Set the cursor position cache for ADDRESS to POS."
497 (puthash address pos elpher-pos-cache))
502 (defun elpher-make-page (display-string address)
503 "Create a page with DISPLAY-STRING and ADDRESS."
504 (list display-string address))
506 (defun elpher-page-display-string (page)
507 "Retrieve the display string corresponding to PAGE."
510 (defun elpher-page-address (page)
511 "Retrieve the address corresponding to PAGE."
514 (defun elpher-page-set-address (page new-address)
515 "Set the address corresponding to PAGE to NEW-ADDRESS."
516 (setcar (cdr page) new-address))
518 (defvar elpher-current-page nil) ; buffer local
519 (defvar elpher-history nil) ; buffer local
521 (defun elpher-visit-page (page &optional renderer no-history)
522 "Visit PAGE using its own renderer or RENDERER, if non-nil.
523 Additionally, push PAGE onto the stack of previously-visited pages,
524 unless NO-HISTORY is non-nil."
526 (elpher-process-cleanup)
527 (unless (or no-history
528 (equal (elpher-page-address elpher-current-page)
529 (elpher-page-address page)))
530 (push elpher-current-page elpher-history))
531 (setq-local elpher-current-page page)
532 (let* ((address (elpher-page-address page))
533 (type (elpher-address-type address))
534 (type-record (cdr (assoc type elpher-type-map)))
538 (funcall (car type-record)
542 (setq page-links (gethash address elpher--gemini-page-links-cache))
544 (setq elpher--gemini-page-links page-links)))
545 (elpher-visit-previous-page)
547 (`(gopher ,type-char)
548 (error "Unsupported gopher selector type '%c' for '%s'"
549 type-char (elpher-address-to-url address)))
551 (error "Unsupported address type '%S' for '%s'"
552 other (elpher-address-to-url address)))))))
554 (defun elpher-visit-previous-page ()
555 "Visit the previous page in the history."
556 (let ((previous-page (pop elpher-history)))
558 (elpher-visit-page previous-page nil t)
559 (error "No previous page"))))
561 (defun elpher-reload-current-page ()
562 "Reload the current page, discarding any existing cached content."
563 (elpher-cache-content (elpher-page-address elpher-current-page) nil)
564 (elpher-visit-page elpher-current-page))
566 (defun elpher-save-pos ()
567 "Save the current position of point to the current page."
568 (when elpher-current-page
569 (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
571 (defun elpher-restore-pos ()
572 "Restore the position of point to that cached in the current page."
573 (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
576 (goto-char (point-min)))))
579 ;;; Buffer preparation
582 (defvar elpher-buffer-name "*elpher*"
583 "The default name of the Elpher buffer.")
585 (defun elpher-update-header ()
586 "If `elpher-use-header' is true, display current page info in window header."
587 (if elpher-use-header
588 (let* ((display-string (elpher-page-display-string elpher-current-page))
589 (address (elpher-page-address elpher-current-page))
590 (tls-string (if (and (not (elpher-address-special-p address))
591 (member (elpher-address-protocol address)
592 '("gophers" "gemini")))
595 (header (concat display-string
596 (propertize tls-string 'face 'bold))))
597 (setq header-line-format header))))
599 (defmacro elpher-with-clean-buffer (&rest args)
600 "Evaluate ARGS with a clean *elpher* buffer as current."
601 `(with-current-buffer elpher-buffer-name
602 (unless (eq major-mode 'elpher-mode)
603 ;; avoid resetting buffer-local variables
605 (let ((inhibit-read-only t))
606 (setq-local network-security-level
607 (default-value 'network-security-level))
609 (elpher-update-header)
612 (defun elpher-buffer-message (string &optional line)
613 "Replace first line in elpher buffer with STRING.
614 If LINE is non-nil, replace that line instead."
615 (with-current-buffer elpher-buffer-name
616 (let ((inhibit-read-only t))
617 (goto-char (point-min))
620 (let ((data (match-data)))
623 (re-search-forward "^.*$")
624 (replace-match string))
625 (set-match-data data))))))
631 (defvar elpher-user-coding-system nil
632 "User-specified coding system to use for decoding text responses.")
634 (defun elpher-decode (string)
635 "Decode STRING using autodetected or user-specified coding system."
636 (decode-coding-string string
637 (if elpher-user-coding-system
638 elpher-user-coding-system
639 (detect-coding-string string t))))
641 (defun elpher-preprocess-text-response (string)
642 "Preprocess text selector response contained in STRING.
643 This involes decoding the character representation, and clearing
644 away CRs and any terminating period."
645 (elpher-decode (replace-regexp-in-string "\n\\.\n$" "\n"
646 (replace-regexp-in-string "\r" "" string))))
649 ;;; Network error reporting
652 (defun elpher-network-error (address error)
653 "Display ERROR message following unsuccessful negotiation with ADDRESS.
654 ERROR can be either an error object or a string."
655 (elpher-with-clean-buffer
656 (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
657 "When attempting to retrieve " (elpher-address-to-url address) ":\n"
658 (if (stringp error) error (error-message-string error)) "\n"
659 (propertize "\n----------------\n\n" 'face 'error)
660 "Press 'u' to return to the previous page.")))
663 ;;; General network communication
666 (defvar elpher-network-timer nil
667 "Timer used for network connections.")
669 (defvar elpher-use-tls nil
670 "If non-nil, use TLS to communicate with gopher servers.")
672 (defvar elpher-client-certificate nil
673 "If non-nil, contains client certificate details to use for TLS connections.")
675 (defun elpher-process-cleanup ()
676 "Immediately shut down any extant elpher process and timers."
677 (let ((p (get-process "elpher-process")))
678 (if p (delete-process p)))
679 (if (timerp elpher-network-timer)
680 (cancel-timer elpher-network-timer)))
682 (defun elpher-get-host-response (address default-port query-string response-processor
683 &optional use-tls force-ipv4)
684 "Generic function for retrieving data from ADDRESS.
686 When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
687 QUERY-STRING is a string sent to the host specified by ADDRESS to
688 illicet a response. This response is passed as an argument to the
689 function RESPONSE-PROCESSOR.
691 If non-nil, USE-TLS specifies that the connection is to be made over
692 TLS. If set to gemini, the certificate verification will be disabled
693 unless `elpher-gemini-TLS-cert-checks' is non-nil.
695 If non-nil, FORCE-IPV4 causes the network connection to be made over
696 ipv4 only. (The default behaviour when this is not set depends on
697 the host operating system and the local network capabilities."
698 (if (and use-tls (not (gnutls-available-p)))
699 (error "Use of TLS requires Emacs to be compiled with GNU TLS support")
700 (unless (< (elpher-address-port address) 65536)
701 (error "Cannot establish network connection: port number > 65536"))
702 (when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
703 (setq-local network-security-level 'low)
704 (setq-local gnutls-verify-error nil))
706 (let* ((kill-buffer-query-functions nil)
707 (port (elpher-address-port address))
708 (service (if (> port 0) port default-port))
709 (host (elpher-address-host address))
710 (socks (or elpher-socks-always (string-suffix-p ".onion" host)))
711 (response-string-parts nil)
714 (timer (run-at-time elpher-connection-timeout nil
716 (elpher-process-cleanup)
718 ; Try again with IPv4
719 ((not (or force-ipv4 socks))
720 (message "Connection timed out. Retrying with IPv4.")
721 (elpher-get-host-response address default-port
726 (not (eq use-tls 'gemini))
727 (or elpher-auto-disengage-TLS
729 "TLS connetion failed. Disable TLS mode and retry? ")))
730 (setq elpher-use-tls nil)
731 (elpher-get-host-response address default-port
736 (elpher-network-error address "Connection time-out."))))))
737 (gnutls-params (list :type 'gnutls-x509pki :hostname host
738 :keylist (elpher-get-current-keylist address)))
739 (proc (if socks (socks-open-network-stream "elpher-process" nil host service)
740 (make-network-process :name "elpher-process"
742 :family (and force-ipv4 'ipv4)
748 (cons 'gnutls-x509pki
749 (apply #'gnutls-boot-parameters
751 (setq elpher-network-timer timer)
752 (set-process-coding-system proc 'binary 'binary)
753 (set-process-query-on-exit-flag proc nil)
754 (elpher-buffer-message (concat "Connecting to " host "..."
755 " (press 'u' to abort)"))
756 (set-process-filter proc
757 (lambda (_proc string)
761 (setq bytes-received (+ bytes-received (length string)))
762 (let ((new-hkbytes-received (/ bytes-received 102400)))
763 (when (> new-hkbytes-received hkbytes-received)
764 (setq hkbytes-received new-hkbytes-received)
765 (elpher-buffer-message
767 (number-to-string (/ hkbytes-received 10.0))
770 (setq response-string-parts
771 (cons string response-string-parts))))
772 (set-process-sentinel proc
775 (cancel-timer timer))
776 (condition-case the-error
778 ((string-prefix-p "open" event) ; request URL
779 (elpher-buffer-message
780 (concat "Connected to " host ". Receiving data..."
781 " (press 'u' to abort)"))
782 (let ((inhibit-eol-conversion t))
783 (process-send-string proc query-string)))
784 ((string-prefix-p "deleted" event)) ; do nothing
785 ((and (not response-string-parts)
786 (not (or elpher-ipv4-always force-ipv4 socks)))
787 ; Try again with IPv4
788 (message "Connection failed. Retrying with IPv4.")
789 (elpher-get-host-response address default-port
793 (response-string-parts
794 (elpher-with-clean-buffer
795 (insert "Data received. Rendering..."))
796 (funcall response-processor
797 (apply #'concat (reverse response-string-parts)))
798 (elpher-restore-pos))
800 (error "No response from server")))
802 (elpher-network-error address the-error)))))
804 (if use-tls (apply #'gnutls-negotiate :process proc gnutls-params))
805 (funcall (process-sentinel proc) proc "open\n")))
807 (error "Error initiating connection to server")))))
810 ;;; Client-side TLS Certificate Management
813 (defun elpher-generate-certificate (common-name key-file cert-file &optional temporary)
814 "Generate a key and a self-signed client TLS certificate using openssl.
816 The Common Name field of the certificate is set to COMMON-NAME. The
817 arguments KEY-FILE and CERT-FILE should contain the absolute paths of
818 the key and certificate files to write.
820 If TEMPORARY is non-nil, the certificate will be given an exporation
821 period of one day, and the key and certificate files will be deleted
822 when the certificate is no longer needed for the current session.
824 Otherwise, the certificate will be given a 100 year expiration period
825 and the files will not be deleted.
827 The function returns a list containing the current host name, the
828 temporary flag, and the key and cert file names in the form required
829 by `gnutls-boot-parameters`."
830 (let ((exp-key-file (expand-file-name key-file))
831 (exp-cert-file (expand-file-name cert-file)))
834 (call-process elpher-openssl-command nil nil nil
835 "req" "-x509" "-newkey" "rsa:2048"
836 "-days" (if temporary "1" "36500")
838 "-subj" (concat "/CN=" common-name)
839 "-keyout" exp-key-file
840 "-out" exp-cert-file)
841 (list (elpher-address-host (elpher-page-address elpher-current-page))
842 temporary exp-key-file exp-cert-file))
844 (message "Check that openssl is installed, or customize `elpher-openssl-command`.")
845 (error "Program 'openssl', required for certificate generation, not found")))))
847 (defun elpher-generate-throwaway-certificate ()
848 "Generate and return details of a throwaway certificate.
849 The key and certificate files will be deleted when they are no
850 longer needed for this session."
851 (let* ((file-base (make-temp-name "elpher"))
852 (key-file (concat temporary-file-directory file-base ".key"))
853 (cert-file (concat temporary-file-directory file-base ".crt")))
854 (elpher-generate-certificate file-base key-file cert-file t)))
856 (defun elpher-generate-persistent-certificate (file-base common-name)
857 "Generate and return details of a persistent certificate.
858 The argument FILE-BASE is used as the base for the key and certificate
859 files, while COMMON-NAME specifies the common name field of the
862 The key and certificate files are written to in `elpher-certificate-directory'."
863 (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
864 (cert-file (concat elpher-certificate-directory file-base ".crt")))
865 (elpher-generate-certificate common-name key-file cert-file)))
867 (defun elpher-get-existing-certificate (file-base)
868 "Return a certificate object corresponding to an existing certificate.
869 It is assumed that the key files FILE-BASE.key and FILE-BASE.crt exist in
870 the directory `elpher-certificate-directory'."
871 (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
872 (cert-file (concat elpher-certificate-directory file-base ".crt")))
873 (list (elpher-address-host (elpher-page-address elpher-current-page))
875 (expand-file-name key-file)
876 (expand-file-name cert-file))))
878 (defun elpher-install-and-use-existing-certificate (key-file-src cert-file-src file-base)
879 "Install a key+certificate file pair in `elpher-certificate-directory'.
880 The strings KEY-FILE-SRC and CERT-FILE-SRC are the existing key and
881 certificate files to install. The argument FILE-BASE is used as the
882 base for the installed key and certificate files."
883 (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
884 (cert-file (concat elpher-certificate-directory file-base ".crt")))
885 (if (or (file-exists-p key-file)
886 (file-exists-p cert-file))
887 (error "A certificate with base name %s is already installed" file-base))
888 (copy-file key-file-src key-file)
889 (copy-file cert-file-src cert-file)
890 (list (elpher-address-host (elpher-page-address elpher-current-page))
892 (expand-file-name key-file)
893 (expand-file-name cert-file))))
895 (defun elpher-list-existing-certificates ()
896 "Return a list of the persistent certificates in `elpher-certificate-directory'."
897 (unless (file-directory-p elpher-certificate-directory)
898 (make-directory elpher-certificate-directory))
901 (file-name-sans-extension file))
902 (directory-files elpher-certificate-directory nil "\\.key$")))
904 (defun elpher-forget-current-certificate ()
905 "Causes any current certificate to be forgotten.)
906 In the case of throwaway certificates, the key and certificate files
909 (when elpher-client-certificate
910 (unless (and (called-interactively-p 'any)
911 (not (y-or-n-p (concat "Really forget client certificate? "
912 "(Throwaway certificates will be deleted.)"))))
913 (when (cadr elpher-client-certificate)
914 (delete-file (elt elpher-client-certificate 2))
915 (delete-file (elt elpher-client-certificate 3)))
916 (setq elpher-client-certificate nil)
917 (if (called-interactively-p 'any)
918 (message "Client certificate forgotten.")))))
920 (defun elpher-get-current-keylist (address)
921 "Retrieve the `gnutls-boot-parameters'-compatable keylist.
923 This is obtained from the client certificate described by
924 `elpher-current-certificate', if one is available and the host for
925 that certificate matches the host in ADDRESS.
927 If `elpher-current-certificate' is non-nil, and its host name doesn't
928 match that of ADDRESS, the certificate is forgotten."
929 (if elpher-client-certificate
930 (if (string= (car elpher-client-certificate)
931 (elpher-address-host address))
932 (list (cddr elpher-client-certificate))
933 (elpher-forget-current-certificate)
934 (message "Disabling client certificate for new host")
939 ;;; Gopher selector retrieval
942 (defun elpher-get-gopher-response (address renderer)
943 "Get response string from gopher server at ADDRESS and render using RENDERER."
944 (elpher-get-host-response address 70
945 (concat (elpher-gopher-address-selector address) "\r\n")
947 (or (string= (elpher-address-protocol address) "gophers")
950 (defun elpher-get-gopher-page (renderer)
951 "Getter function for gopher pages.
952 The RENDERER procedure is used to display the contents of the page
953 once they are retrieved from the gopher server."
954 (let* ((address (elpher-page-address elpher-current-page))
955 (content (elpher-get-cached-content address)))
956 (if (and content (funcall renderer nil))
957 (elpher-with-clean-buffer
959 (elpher-restore-pos))
960 (elpher-with-clean-buffer
961 (insert "LOADING... (use 'u' to cancel)\n"))
962 (condition-case the-error
963 (elpher-get-gopher-response address renderer)
965 (elpher-network-error address the-error))))))
969 (defun elpher-insert-index (string)
970 "Insert the index corresponding to STRING into the current buffer."
971 ;; Should be able to split directly on CRLF, but some non-conformant
972 ;; LF-only servers sadly exist, hence the following.
973 (let ((str-processed (elpher-preprocess-text-response string)))
974 (dolist (line (split-string str-processed "\n"))
976 (unless (= (length line) 0)
977 (let* ((type (elt line 0))
978 (fields (split-string (substring line 1) "\t"))
979 (display-string (elt fields 0))
980 (selector (elt fields 1))
981 (host (elt fields 2))
982 (port (if (elt fields 3)
983 (string-to-number (elt fields 3))
985 (address (elpher-make-gopher-address type selector host port)))
986 (elpher-insert-index-record display-string address)))))))
988 (defun elpher-insert-margin (&optional type-name)
989 "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
992 (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
994 (propertize "[" 'face 'elpher-margin-brackets)
995 (propertize type-name 'face 'elpher-margin-key)
996 (propertize "]" 'face 'elpher-margin-brackets))))
998 (insert (make-string elpher-margin-width ?\s))))
1000 (defun elpher--page-button-help (_window buffer pos)
1001 "Function called by Emacs to generate mouse-over text.
1002 The arguments specify the BUFFER and the POS within the buffer of the item
1003 for which help is required. The function returns the help to be
1004 displayed. The _WINDOW argument is currently unused."
1005 (with-current-buffer buffer
1006 (let ((button (button-at pos)))
1008 (let* ((page (button-get button 'elpher-page))
1009 (address (elpher-page-address page)))
1010 (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
1012 (elpher-address-to-url address))))))))
1014 (defun elpher-insert-index-record (display-string &optional address)
1015 "Function to insert an index record into the current buffer.
1016 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
1017 If ADDRESS is not supplied or nil the record is rendered as an
1018 'information' line."
1019 (let* ((type (if address (elpher-address-type address) nil))
1020 (type-map-entry (cdr (assoc type elpher-type-map))))
1022 (let* ((margin-code (elt type-map-entry 2))
1023 (face (elt type-map-entry 3))
1024 (filtered-display-string (elpher-color-filter-apply display-string))
1025 (page (elpher-make-page filtered-display-string address)))
1026 (elpher-insert-margin margin-code)
1027 (insert-text-button filtered-display-string
1030 'action #'elpher-click-link
1032 'help-echo #'elpher--page-button-help))
1034 ('nil ;; Information
1035 (elpher-insert-margin)
1036 (let ((propertized-display-string
1037 (propertize display-string 'face 'elpher-info)))
1038 (insert (elpher-process-text-for-display propertized-display-string))))
1039 (`(gopher ,selector-type) ;; Unknown
1040 (elpher-insert-margin (concat (char-to-string selector-type) "?"))
1041 (insert (propertize display-string
1042 'face 'elpher-unknown)))))
1045 (defun elpher-click-link (button)
1046 "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
1047 (let ((page (button-get button 'elpher-page)))
1048 (elpher-visit-page page)))
1050 (defun elpher-render-index (data &optional _mime-type-string)
1051 "Render DATA as an index. MIME-TYPE-STRING is unused."
1052 (elpher-with-clean-buffer
1055 (elpher-insert-index data)
1056 (elpher-cache-content (elpher-page-address elpher-current-page)
1061 (defconst elpher-url-regex
1062 "\\([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_~?/@|#-]\\)?\\)?"
1063 "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
1065 (defun elpher-buttonify-urls (string)
1066 "Turn substrings which look like urls in STRING into clickable buttons."
1069 (goto-char (point-min))
1070 (while (re-search-forward elpher-url-regex nil t)
1071 (let ((page (elpher-make-page (substring-no-properties (match-string 0))
1072 (elpher-address-from-url (match-string 0)))))
1073 (make-text-button (match-beginning 0)
1076 'action #'elpher-click-link
1078 'help-echo #'elpher--page-button-help
1082 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
1083 "Incomplete regexp used to strip out some troublesome ANSI escape sequences.")
1085 (defun elpher-process-text-for-display (string)
1086 "Perform any desired processing of STRING prior to display as text.
1087 Currently includes buttonifying URLs and processing ANSI escape codes."
1088 (elpher-buttonify-urls (if elpher-filter-ansi-from-text
1089 (elpher-color-filter-apply string)
1090 (elpher-color-apply string))))
1092 (defun elpher-render-text (data &optional _mime-type-string)
1093 "Render DATA as text. MIME-TYPE-STRING is unused."
1094 (elpher-with-clean-buffer
1097 (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
1098 (elpher-cache-content
1099 (elpher-page-address elpher-current-page)
1104 (defun elpher-render-image (data &optional _mime-type-string)
1105 "Display DATA as image. MIME-TYPE-STRING is unused."
1108 (if (display-images-p)
1110 (let ((image (create-image
1113 (elpher-with-clean-buffer
1114 (insert-image image)
1115 (elpher-restore-pos))))
1116 (elpher-render-download data))))
1118 ;; Search retrieval and rendering
1120 (defun elpher-get-gopher-query-page (renderer)
1121 "Getter for gopher addresses requiring input.
1122 The response is rendered using the rendering function RENDERER."
1123 (let* ((address (elpher-page-address elpher-current-page))
1124 (content (elpher-get-cached-content address))
1126 (if (and content (funcall renderer nil))
1127 (elpher-with-clean-buffer
1129 (elpher-restore-pos)
1130 (message "Displaying cached search results. Reload to perform a new search."))
1132 (let* ((query-string (read-string "Query: "))
1133 (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
1134 (search-address (elpher-make-gopher-address ?1
1136 (elpher-address-host address)
1137 (elpher-address-port address)
1138 (equal (elpher-address-type address) "gophers"))))
1141 (elpher-with-clean-buffer
1142 (insert "LOADING RESULTS... (use 'u' to cancel)"))
1143 (elpher-get-gopher-response search-address renderer))
1145 (elpher-visit-previous-page))))))
1147 ;; Raw server response rendering
1149 (defun elpher-render-raw (data &optional mime-type-string)
1150 "Display raw DATA in buffer. MIME-TYPE-STRING is also displayed if provided."
1153 (elpher-with-clean-buffer
1154 (when mime-type-string
1155 (insert "MIME type specified by server: '" mime-type-string "'\n"))
1157 (goto-char (point-min)))
1158 (message "Displaying raw server response. Reload or redraw to return to standard view.")))
1160 ;; File save "rendering"
1162 (defun elpher-render-download (data &optional _mime-type-string)
1163 "Save DATA to file. MIME-TYPE-STRING is unused."
1166 (let* ((address (elpher-page-address elpher-current-page))
1167 (selector (if (elpher-address-gopher-p address)
1168 (elpher-gopher-address-selector address)
1169 (elpher-address-filename address))))
1170 (elpher-visit-previous-page) ; Do first in case of non-local exits.
1171 (let* ((filename-proposal (file-name-nondirectory selector))
1172 (filename (read-file-name "Download complete. Save file as: "
1174 (if (> (length filename-proposal) 0)
1177 (let ((coding-system-for-write 'binary))
1178 (with-temp-file filename
1180 (message (format "Saved to file %s." filename))))))
1184 (defun elpher-render-html (data &optional _mime-type-string)
1185 "Render DATA as HTML using shr. MIME-TYPE-STRING is unused."
1186 (elpher-with-clean-buffer
1189 (let ((dom (with-temp-buffer
1191 (libxml-parse-html-region (point-min) (point-max)))))
1192 (shr-insert-document dom)))))
1194 ;; Gemini page retrieval
1196 (defvar elpher-gemini-redirect-chain)
1198 (defun elpher-get-gemini-response (address renderer)
1199 "Get response string from gemini server at ADDRESS and render using RENDERER."
1200 (elpher-get-host-response address 1965
1201 (concat (elpher-address-to-url address) "\r\n")
1202 (lambda (response-string)
1203 (elpher-process-gemini-response response-string renderer))
1206 (defun elpher-parse-gemini-response (response)
1207 "Parse the RESPONSE string and return a list of components.
1208 The list is of the form (code meta body). A response of nil implies
1209 that the response was malformed."
1210 (let ((header-end-idx (string-match "\r\n" response)))
1212 (let ((header (string-trim (substring response 0 header-end-idx)))
1213 (body (substring response (+ header-end-idx 2))))
1214 (if (>= (length header) 2)
1215 (let ((code (substring header 0 2))
1216 (meta (string-trim (substring header 2))))
1217 (list code meta body))
1218 (error "Malformed response: No response status found in header %s" header)))
1219 (error "Malformed response: No CRLF-delimited header found in response %s" response))))
1221 (defun elpher-process-gemini-response (response-string renderer)
1222 "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
1223 (let ((response-components (elpher-parse-gemini-response response-string)))
1224 (let ((response-code (elt response-components 0))
1225 (response-meta (elt response-components 1))
1226 (response-body (elt response-components 2)))
1227 (pcase (elt response-code 0)
1228 (?1 ; Input required
1229 (elpher-with-clean-buffer
1230 (insert "Gemini server is requesting input."))
1231 (let* ((query-string
1232 (if (eq (elt response-code 1) ?1)
1233 (read-passwd (concat response-meta ": "))
1234 (read-string (concat response-meta ": "))))
1235 (query-address (seq-copy (elpher-page-address elpher-current-page)))
1236 (old-fname (url-filename query-address)))
1237 (setf (url-filename query-address)
1238 (concat old-fname "?" (url-build-query-string `((,query-string)))))
1239 (elpher-get-gemini-response query-address renderer)))
1240 (?2 ; Normal response
1241 (funcall renderer response-body response-meta))
1243 (message "Following redirect to %s" response-meta)
1244 (if (>= (length elpher-gemini-redirect-chain) 5)
1245 (error "More than 5 consecutive redirects followed"))
1246 (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1247 (if (member redirect-address elpher-gemini-redirect-chain)
1248 (error "Redirect loop detected"))
1249 (if (not (string= (elpher-address-protocol redirect-address)
1251 (error "Server tried to automatically redirect to non-gemini URL: %s"
1253 (elpher-page-set-address elpher-current-page redirect-address)
1254 (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1255 (elpher-get-gemini-response redirect-address renderer)))
1256 (?4 ; Temporary failure
1257 (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1258 response-code response-meta))
1259 (?5 ; Permanent failure
1260 (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1261 response-code response-meta))
1262 (?6 ; Client certificate required
1263 (elpher-with-clean-buffer
1264 (if elpher-client-certificate
1265 (insert "Gemini server does not recognise the provided TLS certificate:\n\n")
1266 (insert "Gemini server is requesting a valid TLS certificate:\n\n"))
1268 (elpher-gemini-insert-text response-meta))
1269 (let ((chosen-certificate (elpher-choose-client-certificate)))
1270 (unless chosen-certificate
1271 (error "Gemini server requires a client certificate and none was provided"))
1272 (setq elpher-client-certificate chosen-certificate))
1273 (elpher-with-clean-buffer)
1274 (elpher-get-gemini-response (elpher-page-address elpher-current-page) renderer))
1276 (error "Gemini server response unknown: %s %s"
1277 response-code response-meta))))))
1279 (unless (fboundp 'read-answer)
1280 (defun read-answer (question answers)
1281 "Backfill for the new read-answer code."
1282 (completing-read question (mapcar 'identity answers))))
1284 (defun elpher-choose-client-certificate ()
1285 "Prompt for a client certificate to use to establish a TLS connection."
1286 (let* ((read-answer-short t))
1287 (pcase (read-answer "What do you want to do? "
1289 "generate and use throw-away certificate")
1291 "generate new or use existing persistent certificate")
1293 "stop immediately")))
1295 (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1297 (let* ((existing-certificates (elpher-list-existing-certificates))
1298 (file-base (completing-read
1299 "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1300 existing-certificates)))
1301 (if (string-empty-p (string-trim file-base))
1303 (if (member file-base existing-certificates)
1304 (setq elpher-client-certificate
1305 (elpher-get-existing-certificate file-base))
1306 (pcase (read-answer "Generate new certificate or install externally-generated one? "
1308 "generate new certificate")
1310 "install existing certificate")
1312 "stop immediately")))
1314 (let ((common-name (read-string "Common Name field for new certificate: "
1316 (message "New key and self-signed certificate written to %s"
1317 elpher-certificate-directory)
1318 (elpher-generate-persistent-certificate file-base common-name)))
1320 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1321 (key-file (read-file-name "Key file: " nil nil t)))
1322 (message "Key and certificate installed in %s for future use"
1323 elpher-certificate-directory)
1324 (elpher-install-and-use-existing-certificate key-file
1330 (defun elpher-get-gemini-page (renderer)
1331 "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1332 (let* ((address (elpher-page-address elpher-current-page))
1333 (content (elpher-get-cached-content address)))
1334 (condition-case the-error
1335 (if (and content (funcall renderer nil))
1336 (elpher-with-clean-buffer
1338 (elpher-restore-pos))
1339 (elpher-with-clean-buffer
1340 (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1341 (setq elpher-gemini-redirect-chain nil)
1342 (elpher-get-gemini-response address renderer))
1344 (elpher-network-error address the-error)))))
1346 (defun elpher-render-gemini (body &optional mime-type-string)
1347 "Render gemini response BODY with rendering MIME-TYPE-STRING."
1350 (let* ((mime-type-string* (if (or (not mime-type-string)
1351 (string-empty-p mime-type-string))
1352 "text/gemini; charset=utf-8"
1354 (mime-type-split (split-string mime-type-string* ";" t))
1355 (mime-type (string-trim (car mime-type-split)))
1356 (parameters (mapcar (lambda (s)
1357 (let ((key-val (split-string s "=")))
1358 (list (downcase (string-trim (car key-val)))
1359 (downcase (string-trim (cadr key-val))))))
1360 (cdr mime-type-split))))
1361 (when (string-prefix-p "text/" mime-type)
1362 (setq body (decode-coding-string
1364 (if (assoc "charset" parameters)
1365 (intern (cadr (assoc "charset" parameters)))
1367 (setq body (replace-regexp-in-string "\r" "" body)))
1369 ((or "text/gemini" "")
1370 (elpher-render-gemini-map body parameters))
1372 (elpher-render-html body))
1373 ((pred (string-prefix-p "text/"))
1374 (elpher-render-gemini-plain-text body parameters))
1375 ((pred (string-prefix-p "image/"))
1376 (elpher-render-image body))
1378 (elpher-render-download body))))))
1380 (defun elpher-gemini-get-link-url (link-line)
1381 "Extract the url portion of LINK-LINE, a gemini map file link line.
1382 Returns nil in the event that the contents of the line following the
1383 => prefix are empty."
1384 (let ((l (split-string (substring link-line 2))))
1386 (string-trim (elt l 0))
1389 (defun elpher-gemini-get-link-display-string (link-line)
1390 "Extract the display string portion of LINK-LINE, a gemini map file link line.
1391 Returns the url portion in the event that the display-string portion is empty."
1392 (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1393 (idx (string-match "[ \t]" rest)))
1394 (string-trim (if idx
1395 (substring rest (+ idx 1))
1398 (defun elpher-collapse-dot-sequences (filename)
1399 "Collapse dot sequences in FILENAME.
1400 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1401 (let* ((path (split-string filename "/"))
1402 (path-reversed-normalized
1403 (seq-reduce (lambda (a b)
1404 (cond ((and a (equal b "..") (cdr a)))
1405 ((and (not a) (equal b "..")) a) ;leading .. are dropped
1409 (string-join (reverse path-reversed-normalized) "/")))
1411 (defun elpher-address-from-gemini-url (url)
1412 "Extract address from URL with defaults as per gemini map files.
1413 While there's obviously some redundancy here between this function and
1414 `elpher-address-from-url', gemini map file URLs require enough special
1415 treatment that a separate function is warranted."
1416 (let ((address (url-generic-parse-url url))
1417 (current-address (elpher-page-address elpher-current-page)))
1418 (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1419 (setf (url-fullness address) t)
1420 (if (url-host address) ;if there is an explicit host, filenames are absolute
1421 (if (string-empty-p (url-filename address))
1422 (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1423 (setf (url-host address) (url-host current-address))
1424 (setf (url-port address) (url-port current-address))
1425 (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1426 (setf (url-filename address)
1427 (concat (file-name-directory (url-filename current-address))
1428 (url-filename address)))))
1429 (unless (url-type address)
1430 (setf (url-type address) "gemini"))
1431 (when (equal (url-type address) "gemini")
1432 (setf (url-filename address)
1433 (elpher-collapse-dot-sequences (url-filename address)))))
1434 (elpher-remove-redundant-ports address)))
1436 (defun elpher-gemini-insert-link (link-line)
1437 "Insert link described by LINK-LINE into a text/gemini document."
1438 (let* ((url (elpher-gemini-get-link-url link-line))
1439 (display-string (elpher-gemini-get-link-display-string link-line))
1440 (address (elpher-address-from-gemini-url url))
1441 (type (if address (elpher-address-type address) nil))
1442 (type-map-entry (cdr (assoc type elpher-type-map))))
1443 (setq elpher--gemini-page-links (append elpher--gemini-page-links `(,address)))
1444 (when display-string
1445 (insert elpher-gemini-link-string)
1447 (let* ((face (elt type-map-entry 3))
1448 (filtered-display-string (elpher-color-filter-apply display-string))
1449 (page (elpher-make-page filtered-display-string address)))
1450 (insert-text-button filtered-display-string
1453 'action #'elpher-click-link
1455 'help-echo #'elpher--page-button-help))
1456 (insert (propertize display-string 'face 'elpher-unknown)))
1459 (defun elpher-gemini-insert-header (header-line)
1460 "Insert header described by HEADER-LINE into a text/gemini document.
1461 The gemini map file line describing the header is given
1463 (when (string-match "^\\(#+\\)[ \t]*" header-line)
1464 (let* ((level (length (match-string 1 header-line)))
1465 (header (substring header-line (match-end 0)))
1467 (1 'elpher-gemini-heading1)
1468 (2 'elpher-gemini-heading2)
1469 (3 'elpher-gemini-heading3)
1471 (fill-column (if (display-graphic-p)
1473 (font-get (font-spec :name (face-font 'default)) :size))
1474 (font-get (font-spec :name (face-font face)) :size)) fill-column)))
1475 (setq elpher--gemini-page-headings (cons (cons header (point))
1476 elpher--gemini-page-headings))
1477 (unless (display-graphic-p)
1478 (insert (make-string level ?#) " "))
1479 (insert (propertize header 'face face))
1482 (defun elpher-gemini-insert-text (text-line)
1483 "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1484 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1485 width defined by `elpher-gemini-max-fill-width'."
1486 (string-match "\\(^[ \t]*\\)\\(\\*[ \t]+\\|>[ \t]*\\)?" text-line)
1487 (let* ((line-prefix (match-string 2 text-line))
1488 (processed-text-line
1490 (cond ((string-prefix-p "*" line-prefix)
1492 (replace-regexp-in-string "\\*"
1493 elpher-gemini-bullet-string
1494 (match-string 0 text-line))
1495 (substring text-line (match-end 0))))
1496 ((string-prefix-p ">" line-prefix)
1497 (propertize text-line 'face 'elpher-gemini-quoted))
1500 (adaptive-fill-mode t)
1501 ;; fill-prefix is important for adaptive-fill-mode: without
1502 ;; it, multi-line list items are not indented correct
1503 (fill-prefix (if (match-string 2 text-line)
1504 (replace-regexp-in-string "[>\*]" " " (match-string 0 text-line))
1506 (insert (elpher-process-text-for-display processed-text-line))
1509 (defun elpher-render-gemini-map (data _parameters)
1510 "Render DATA as a gemini map file, PARAMETERS is currently unused."
1511 (elpher-with-clean-buffer
1512 (setq elpher--gemini-page-headings nil)
1513 (let ((preformatted nil)
1516 (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1517 (setq elpher--gemini-page-links '())
1518 (dolist (line (split-string data "\n"))
1520 ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1521 (preformatted (insert (elpher-process-text-for-display
1522 (propertize line 'face 'elpher-gemini-preformatted))
1524 ((string-prefix-p "=>" line)
1526 (if elpher-gemini-number-links
1530 (number-to-string link-counter)
1532 (setq link-counter (1+ link-counter))
1533 (elpher-gemini-insert-link line)))
1534 ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1535 (t (elpher-gemini-insert-text line)))))
1536 (setq elpher--gemini-page-headings (nreverse elpher--gemini-page-headings))
1537 (elpher-cache-content
1538 (elpher-page-address elpher-current-page)
1541 (elpher-page-address elpher-current-page)
1542 elpher--gemini-page-links
1543 elpher--gemini-page-links-cache)))
1545 (defun elpher-render-gemini-plain-text (data _parameters)
1546 "Render DATA as plain text file. PARAMETERS is currently unused."
1547 (elpher-with-clean-buffer
1548 (insert (elpher-process-text-for-display data))
1549 (elpher-cache-content
1550 (elpher-page-address elpher-current-page)
1554 ;; Finger page connection
1556 (defun elpher-get-finger-page (renderer)
1557 "Opens a finger connection to the current page address.
1558 The result is rendered using RENDERER."
1559 (let* ((address (elpher-page-address elpher-current-page))
1560 (content (elpher-get-cached-content address)))
1561 (if (and content (funcall renderer nil))
1562 (elpher-with-clean-buffer
1564 (elpher-restore-pos))
1565 (elpher-with-clean-buffer
1566 (insert "LOADING... (use 'u' to cancel)\n"))
1567 (condition-case the-error
1568 (let* ((kill-buffer-query-functions nil)
1569 (user (let ((filename (elpher-address-filename address)))
1570 (if (> (length filename) 1)
1571 (substring filename 1)
1572 (elpher-address-user address)))))
1573 (elpher-get-host-response address 79
1574 (concat user "\r\n")
1577 (elpher-network-error address the-error))))))
1580 ;; Telnet page connection
1582 (defun elpher-get-telnet-page (renderer)
1583 "Opens a telnet connection to the current page address (RENDERER must be nil)."
1585 (elpher-visit-previous-page)
1586 (error "Command not supported for telnet URLs"))
1587 (let* ((address (elpher-page-address elpher-current-page))
1588 (host (elpher-address-host address))
1589 (port (elpher-address-port address)))
1590 (elpher-visit-previous-page)
1596 ;; Other URL page opening
1598 (defun elpher-get-other-url-page (renderer)
1599 "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1601 (elpher-visit-previous-page)
1602 (error "Command not supported for general URLs"))
1603 (let* ((address (elpher-page-address elpher-current-page))
1604 (url (elpher-address-to-url address)))
1606 (elpher-visit-previous-page) ; Do first in case of non-local exits.
1607 (message "Opening URL...")
1608 (if elpher-open-urls-with-eww
1610 (browse-url url)))))
1613 ;; Start page page retrieval
1615 (defun elpher-get-start-page (renderer)
1616 "Getter which displays the start page (RENDERER must be nil)."
1618 (elpher-visit-previous-page)
1619 (error "Command not supported for start page"))
1620 (elpher-with-clean-buffer
1621 (insert " --------------------------------------------\n"
1622 " Elpher Gopher and Gemini Client \n"
1623 " version " elpher-version "\n"
1624 " --------------------------------------------\n"
1626 "Default bindings:\n"
1628 " - TAB/Shift-TAB: next/prev item on current page\n"
1629 " - RET/mouse-1: open item under cursor\n"
1630 " - m: select an item on current page by name (autocompletes)\n"
1631 " - u/mouse-3/U: return to previous page or to the start page\n"
1632 " - o/O: visit different selector or the root menu of the current server\n"
1633 " - g: go to a particular address (gopher, gemini, finger)\n"
1634 " - v: visit a numbered link on a gemini page\n"
1635 " - d/D: download item under cursor or current page\n"
1636 " - i/I: info on item under cursor or current page\n"
1637 " - c/C: copy URL representation of item under cursor or current page\n"
1638 " - a/A: bookmark the item under cursor or current page\n"
1639 " - x/X: remove bookmark for item under cursor or current page\n"
1640 " - B: visit the bookmarks page\n"
1641 " - r: redraw current page (using cached contents if available)\n"
1642 " - R: reload current page (regenerates cache)\n"
1643 " - S: set character coding system for gopher (default is to autodetect)\n"
1644 " - T: toggle TLS gopher mode\n"
1645 " - F: forget/discard current TLS client certificate\n"
1646 " - .: display the raw server response for the current page\n"
1648 "Start your exploration of gopher space and gemini:\n")
1649 (elpher-insert-index-record "Floodgap Systems Gopher Server"
1650 (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1651 (elpher-insert-index-record "Project Gemini home page"
1652 (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1654 "Alternatively, select a search engine and enter some search terms:\n")
1655 (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1656 (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1657 (elpher-insert-index-record "Gemini Search Engine (geminispace.info)"
1658 (elpher-address-from-url "gemini://geminispace.info/search"))
1660 "This page contains your bookmarked sites (also visit with B):\n")
1661 (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1663 "For Elpher release news or to leave feedback, visit:\n")
1664 (elpher-insert-index-record "The Elpher Project Page"
1665 (elpher-make-gopher-address ?1
1671 (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1672 (insert-text-button "Elpher info manual"
1678 'help-echo help-string))
1679 (insert " for the full documentation. **\n")
1681 (concat " (This should be available if you have installed Elpher using\n"
1682 " MELPA. Otherwise you will have to install the manual yourself.)\n")
1684 (elpher-restore-pos)))
1686 ;; Bookmarks page page retrieval
1688 (defun elpher-get-bookmarks-page (renderer)
1689 "Getter to load and display the current bookmark list (RENDERER must be nil)."
1691 (elpher-visit-previous-page)
1692 (error "Command not supported for bookmarks page"))
1693 (elpher-with-clean-buffer
1694 (insert "---- Bookmark list ----\n\n")
1695 (let ((bookmarks (elpher-load-bookmarks)))
1697 (dolist (bookmark bookmarks)
1698 (let ((display-string (elpher-bookmark-display-string bookmark))
1699 (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1700 (elpher-insert-index-record display-string address)))
1701 (insert "No bookmarks found.\n")))
1702 (insert "\n-----------------------\n"
1704 "- u: return to previous page\n"
1705 "- x: delete selected bookmark\n"
1706 "- a: rename selected bookmark\n"
1708 "Bookmarks are stored in the file ")
1709 (let ((filename elpher-bookmarks-file)
1710 (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1711 (insert-text-button filename
1715 (find-file filename))
1717 'help-echo help-string))
1719 (elpher-restore-pos)))
1725 (defun elpher-make-bookmark (display-string url)
1726 "Make an elpher bookmark.
1727 DISPLAY-STRING determines how the bookmark will appear in the
1728 bookmark list, while URL is the url of the entry."
1729 (list display-string url))
1731 (defun elpher-bookmark-display-string (bookmark)
1732 "Get the display string of BOOKMARK."
1735 (defun elpher-set-bookmark-display-string (bookmark display-string)
1736 "Set the display string of BOOKMARK to DISPLAY-STRING."
1737 (setcar bookmark display-string))
1739 (defun elpher-bookmark-url (bookmark)
1740 "Get the address for BOOKMARK."
1743 (defun elpher-save-bookmarks (bookmarks)
1744 "Record the bookmark list BOOKMARKS to the user's bookmark file.
1745 Beware that this completely replaces the existing contents of the file."
1746 (let ((bookmark-dir (file-name-directory elpher-bookmarks-file)))
1747 (unless (file-directory-p bookmark-dir)
1748 (make-directory bookmark-dir)))
1749 (with-temp-file elpher-bookmarks-file
1751 (insert "; Elpher bookmarks file\n\n"
1752 "; Bookmarks are stored as a list of (label URL) items.\n"
1753 "; Feel free to edit by hand, but take care to ensure\n"
1754 "; the list structure remains intact.\n\n")
1755 (pp bookmarks (current-buffer))))
1757 (defun elpher-load-bookmarks ()
1758 "Get the list of bookmarks from the users's bookmark file."
1762 (insert-file-contents elpher-bookmarks-file)
1763 (goto-char (point-min))
1764 (read (current-buffer))))))
1765 (if (and bookmarks (listp (cadar bookmarks)))
1767 (message "Reading old bookmark file. (Will be updated on write.)")
1768 (mapcar (lambda (old-bm)
1770 (elpher-address-to-url (apply #'elpher-make-gopher-address
1775 (defun elpher-add-address-bookmark (address display-string)
1776 "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1777 If ADDRESS is already bookmarked, update the label only."
1778 (let ((bookmarks (elpher-load-bookmarks))
1779 (url (elpher-address-to-url address)))
1780 (let ((existing-bookmark (rassoc (list url) bookmarks)))
1781 (if existing-bookmark
1782 (elpher-set-bookmark-display-string existing-bookmark display-string)
1783 (push (elpher-make-bookmark display-string url) bookmarks)))
1784 (elpher-save-bookmarks bookmarks)))
1786 (defun elpher-remove-address-bookmark (address)
1787 "Remove any bookmark to ADDRESS."
1788 (let ((url (elpher-address-to-url address)))
1789 (elpher-save-bookmarks
1790 (seq-filter (lambda (bookmark)
1791 (not (equal (elpher-bookmark-url bookmark) url)))
1792 (elpher-load-bookmarks)))))
1799 ;; Avoid byte compilation warnings.
1801 (declare-function org-link-store-props "ol")
1802 (declare-function org-link-set-parameters "ol"))
1804 (defun elpher-org-export-link (link description format protocol)
1805 "Export a LINK with DESCRIPTION for the given PROTOCOL and FORMAT.
1807 FORMAT is an Org export backend. DESCRIPTION may be nil. PROTOCOL may be one
1808 of gemini, gopher or finger."
1809 (let* ((url (if (equal protocol "elpher")
1810 (string-remove-prefix "elpher:" link)
1811 (format "%s:%s" protocol link)))
1812 (desc (or description url)))
1814 (`gemini (format "=> %s %s" url desc))
1815 (`html (format "<a href=\"%s\">%s</a>" url desc))
1816 (`latex (format "\\href{%s}{%s}" url desc))
1817 (_ (if (not description)
1819 (format "%s (%s)" desc url))))))
1821 (defun elpher-org-store-link ()
1822 "Store link to an `elpher' page in Org."
1823 (when (eq major-mode 'elpher-mode)
1824 (let* ((url (elpher-info-current))
1825 (desc (car elpher-current-page))
1827 ((string-prefix-p "gemini:" url) "gemini")
1828 ((string-prefix-p "gopher:" url) "gopher")
1829 ((string-prefix-p "finger:" url) "finger")
1831 (when (equal "elpher" protocol)
1832 ;; Weird link. Or special inner link?
1833 (setq url (concat "elpher:" url)))
1834 (org-link-store-props :type protocol :link url :description desc)
1837 (defun elpher-org-follow-link (link protocol)
1838 "Visit a LINK for the given PROTOCOL.
1840 PROTOCOL may be one of gemini, gopher or finger. This method also
1841 supports the old protocol elpher, where the link is self-contained."
1842 (let ((url (if (equal protocol "elpher")
1843 (string-remove-prefix "elpher:" link)
1844 (format "%s:%s" protocol link))))
1847 (with-eval-after-load 'org
1848 (org-link-set-parameters
1850 :store #'elpher-org-store-link
1851 :export (lambda (link description format _plist)
1852 (elpher-org-export-link link description format "elpher"))
1853 :follow (lambda (link _arg) (elpher-org-follow-link link "elpher")))
1854 (org-link-set-parameters
1856 :export (lambda (link description format _plist)
1857 (elpher-org-export-link link description format "gemini"))
1858 :follow (lambda (link _arg) (elpher-org-follow-link link "gemini")))
1859 (org-link-set-parameters
1861 :export (lambda (link description format _plist)
1862 (elpher-org-export-link link description format "gopher"))
1863 :follow (lambda (link _arg) (elpher-org-follow-link link "gopher")))
1864 (org-link-set-parameters
1866 :export (lambda (link description format _plist)
1867 (elpher-org-export-link link description format "finger"))
1868 :follow (lambda (link _arg) (elpher-org-follow-link link "finger"))))
1872 ;; Avoid byte compilation warnings.
1874 (defvar thing-at-point-uri-schemes))
1877 (defun elpher-browse-url-elpher (url &rest _args)
1878 "Browse URL using Elpher. This function is used by `browse-url'."
1879 (interactive (browse-url-interactive-arg "Elpher URL: "))
1882 ;; Use elpher to open gopher, finger and gemini links
1883 ;; For recent version of `browse-url' package
1884 (if (boundp 'browse-url-default-handlers)
1886 'browse-url-default-handlers
1887 '("^\\(gopher\\|finger\\|gemini\\)://" . elpher-browse-url-elpher))
1888 ;; Patch `browse-url-browser-function' for older ones. The value of
1889 ;; that variable is `browse-url-default-browser' by default, so
1890 ;; that's the function that gets advised.
1891 (advice-add browse-url-browser-function :before-while
1892 (lambda (url &rest _args)
1893 "Handle gemini, gopher, and finger schemes using Elpher."
1894 (let ((scheme (downcase (car (split-string url ":" t)))))
1895 (if (member scheme '("gemini" "gopher" "finger"))
1896 ;; `elpher-go' always returns nil, which will stop the
1897 ;; advice chain here in a before-while
1899 ;; chain must continue, then return t.
1902 ;; Register "gemini://" as a URI scheme so `browse-url' does the right thing
1903 (with-eval-after-load 'thingatpt
1904 (add-to-list 'thing-at-point-uri-schemes "gemini://"))
1909 (defvar mu4e~view-beginning-of-url-regexp))
1911 (with-eval-after-load 'mu4e-view
1912 ;; Make mu4e aware of the gemini world
1913 (setq mu4e~view-beginning-of-url-regexp
1914 "\\(?:https?\\|gopher\\|finger\\|gemini\\)://\\|mailto:"))
1916 ;;; Interactive procedures
1919 (defun elpher-next-link ()
1920 "Move point to the next link on the current page."
1924 (defun elpher-prev-link ()
1925 "Move point to the previous link on the current page."
1927 (backward-button 1))
1929 (defun elpher-follow-current-link ()
1930 "Open the link or url at point."
1935 (defun elpher-go (host-or-url)
1936 "Go to a particular gopher site HOST-OR-URL.
1937 When run interactively HOST-OR-URL is read from the minibuffer."
1938 (interactive "sGopher or Gemini URL: ")
1939 (let* ((cleaned-host-or-url (string-trim host-or-url))
1940 (address (elpher-address-from-url cleaned-host-or-url))
1941 (page (elpher-make-page cleaned-host-or-url address)))
1942 (switch-to-buffer elpher-buffer-name)
1943 (elpher-with-clean-buffer
1944 (elpher-visit-page page))
1947 (defun elpher-go-current ()
1948 "Go to a particular site read from the minibuffer, initialized with the current URL."
1950 (let ((address (elpher-page-address elpher-current-page)))
1951 (let ((url (read-string "Gopher or Gemini URL: "
1952 (unless (elpher-address-special-p address)
1953 (elpher-address-to-url address)))))
1954 (elpher-visit-page (elpher-make-page url (elpher-address-from-url url))))))
1956 (defun elpher-visit-gemini-numbered-link (n)
1957 "Visit link designated by a number N."
1958 (interactive "nLink number: ")
1959 (if (or (> n (length elpher--gemini-page-links))
1961 (user-error "Invalid link number"))
1962 (let ((address (nth (1- n) elpher--gemini-page-links)))
1963 (elpher-go (url-recreate-url address))))
1965 (defun elpher-redraw ()
1966 "Redraw current page."
1968 (elpher-visit-page elpher-current-page))
1970 (defun elpher-reload ()
1971 "Reload current page."
1973 (elpher-reload-current-page))
1975 (defun elpher-toggle-tls ()
1976 "Toggle TLS encryption mode for gopher."
1978 (setq elpher-use-tls (not elpher-use-tls))
1980 (if (gnutls-available-p)
1981 (message "TLS gopher mode enabled. (Will not affect current page until reload.)")
1982 (setq elpher-use-tls nil)
1983 (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1984 (message "TLS gopher mode disabled. (Will not affect current page until reload.)")))
1986 (defun elpher-view-raw ()
1987 "View raw server response for current page."
1989 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1990 (error "This page was not generated by a server")
1991 (elpher-visit-page elpher-current-page
1992 #'elpher-render-raw)))
1994 (defun elpher-back ()
1995 "Go to previous site."
1997 (elpher-visit-previous-page))
1999 (defun elpher-back-to-start ()
2000 "Go all the way back to the start page."
2002 (setq-local elpher-current-page nil)
2003 (setq-local elpher-history nil)
2004 (elpher-visit-page (elpher-make-start-page)))
2006 (defun elpher-download ()
2007 "Download the link at point."
2009 (let ((button (button-at (point))))
2011 (let ((page (button-get button 'elpher-page)))
2012 (if (elpher-address-special-p (elpher-page-address page))
2013 (error "Cannot download %s"
2014 (elpher-page-display-string page))
2015 (elpher-visit-page (button-get button 'elpher-page)
2016 #'elpher-render-download)))
2017 (error "No link selected"))))
2019 (defun elpher-download-current ()
2020 "Download the current page."
2022 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
2023 (error "Cannot download %s"
2024 (elpher-page-display-string elpher-current-page))
2025 (elpher-visit-page (elpher-make-page
2026 (elpher-page-display-string elpher-current-page)
2027 (elpher-page-address elpher-current-page))
2028 #'elpher-render-download
2031 (defun elpher-build-link-map ()
2032 "Build alist mapping link names to destination pages in current buffer."
2033 (let ((link-map nil)
2034 (b (next-button (point-min) t)))
2036 (push (cons (button-label b) b) link-map)
2037 (setq b (next-button (button-start b))))
2040 (defun elpher-jump ()
2041 "Select a directory entry by name. Similar to the info browser (m)enu command."
2043 (let* ((link-map (elpher-build-link-map)))
2045 (let ((key (let ((completion-ignore-case t))
2046 (completing-read "Directory item/link: "
2048 (if (and key (> (length key) 0))
2049 (let ((b (cdr (assoc key link-map))))
2050 (goto-char (button-start b))
2051 (button-activate b)))))))
2053 (defun elpher-root-dir ()
2054 "Visit root of current server."
2056 (let ((address (elpher-page-address elpher-current-page)))
2057 (if (not (elpher-address-special-p address))
2058 (if (or (member (url-filename address) '("/" ""))
2059 (and (elpher-address-gopher-p address)
2060 (= (length (elpher-gopher-address-selector address)) 0)))
2061 (error "Already at root directory of current server")
2062 (let ((address-copy (elpher-address-from-url
2063 (elpher-address-to-url address))))
2064 (setf (url-filename address-copy) "")
2065 (elpher-go (elpher-address-to-url address-copy))))
2066 (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
2068 (defun elpher-bookmarks-current-p ()
2069 "Return non-nil if current page is a bookmarks page."
2070 (equal (elpher-address-type (elpher-page-address elpher-current-page))
2071 '(special bookmarks)))
2073 (defun elpher-reload-bookmarks ()
2074 "Reload bookmarks if current page is a bookmarks page."
2075 (if (elpher-bookmarks-current-p)
2076 (elpher-reload-current-page)))
2078 (defun elpher-bookmark-current ()
2079 "Bookmark the current page."
2081 (let ((address (elpher-page-address elpher-current-page))
2082 (display-string (elpher-page-display-string elpher-current-page)))
2083 (if (not (elpher-address-special-p address))
2084 (let ((bookmark-display-string (read-string "Bookmark display string: "
2086 (elpher-add-address-bookmark address bookmark-display-string)
2087 (message "Bookmark added."))
2088 (error "Cannot bookmark %s" display-string))))
2090 (defun elpher-bookmark-link ()
2091 "Bookmark the link at point."
2093 (let ((button (button-at (point))))
2095 (let* ((page (button-get button 'elpher-page))
2096 (address (elpher-page-address page))
2097 (display-string (elpher-page-display-string page)))
2098 (if (not (elpher-address-special-p address))
2099 (let ((bookmark-display-string (read-string "Bookmark display string: "
2101 (elpher-add-address-bookmark address bookmark-display-string)
2102 (elpher-reload-bookmarks)
2103 (message "Bookmark added."))
2104 (error "Cannot bookmark %s" display-string)))
2105 (error "No link selected"))))
2107 (defun elpher-unbookmark-current ()
2108 "Remove bookmark for the current page."
2110 (let ((address (elpher-page-address elpher-current-page)))
2111 (when (and (not (elpher-address-special-p address))
2112 (y-or-n-p "Really remove bookmark for the current page? "))
2113 (elpher-remove-address-bookmark address)
2114 (message "Bookmark removed."))))
2116 (defun elpher-unbookmark-link ()
2117 "Remove bookmark for the link at point."
2119 (let ((button (button-at (point))))
2121 (when (y-or-n-p "Really remove bookmark for this link? ")
2122 (let ((page (button-get button 'elpher-page)))
2123 (elpher-remove-address-bookmark (elpher-page-address page))
2124 (elpher-reload-bookmarks)
2125 (message "Bookmark removed.")))
2126 (error "No link selected"))))
2129 (defun elpher-bookmarks ()
2130 "Visit bookmarks page."
2132 (switch-to-buffer elpher-buffer-name)
2134 (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
2136 (defun elpher-info-page (page)
2137 "Display information on PAGE."
2138 (let ((display-string (elpher-page-display-string page))
2139 (address (elpher-page-address page)))
2140 (if (elpher-address-special-p address)
2141 (message "Special page: %s" display-string)
2142 (message "%s" (elpher-address-to-url address)))))
2144 (defun elpher-info-link ()
2145 "Display information on page corresponding to link at point."
2147 (let ((button (button-at (point))))
2149 (elpher-info-page (button-get button 'elpher-page))
2150 (error "No item selected"))))
2152 (defun elpher-info-current ()
2153 "Display information on current page."
2155 (elpher-info-page elpher-current-page))
2157 (defun elpher-copy-page-url (page)
2158 "Copy URL representation of address of PAGE to `kill-ring'."
2159 (let ((address (elpher-page-address page)))
2160 (if (elpher-address-special-p address)
2161 (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
2162 (let ((url (elpher-address-to-url address)))
2163 (message "Copied \"%s\" to kill-ring/clipboard." url)
2166 (defun elpher-copy-link-url ()
2167 "Copy URL of item at point to `kill-ring'."
2169 (let ((button (button-at (point))))
2171 (elpher-copy-page-url (button-get button 'elpher-page))
2172 (error "No item selected"))))
2174 (defun elpher-copy-current-url ()
2175 "Copy URL of current page to `kill-ring'."
2177 (elpher-copy-page-url elpher-current-page))
2179 (defun elpher-set-gopher-coding-system ()
2180 "Specify an explicit character coding system for gopher selectors."
2182 (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
2183 (setq elpher-user-coding-system system)
2185 (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
2186 (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
2192 (defvar elpher-mode-map
2193 (let ((map (make-sparse-keymap)))
2194 (define-key map (kbd "TAB") 'elpher-next-link)
2195 (define-key map (kbd "<backtab>") 'elpher-prev-link)
2196 (define-key map (kbd "C-M-i") 'elpher-prev-link)
2197 (define-key map (kbd "u") 'elpher-back)
2198 (define-key map (kbd "U") 'elpher-back-to-start)
2199 (define-key map [mouse-3] 'elpher-back)
2200 (define-key map (kbd "O") 'elpher-root-dir)
2201 (define-key map (kbd "g") 'elpher-go)
2202 (define-key map (kbd "o") 'elpher-go-current)
2203 (define-key map (kbd "r") 'elpher-redraw)
2204 (define-key map (kbd "R") 'elpher-reload)
2205 (define-key map (kbd "T") 'elpher-toggle-tls)
2206 (define-key map (kbd ".") 'elpher-view-raw)
2207 (define-key map (kbd "d") 'elpher-download)
2208 (define-key map (kbd "D") 'elpher-download-current)
2209 (define-key map (kbd "m") 'elpher-jump)
2210 (define-key map (kbd "i") 'elpher-info-link)
2211 (define-key map (kbd "I") 'elpher-info-current)
2212 (define-key map (kbd "c") 'elpher-copy-link-url)
2213 (define-key map (kbd "C") 'elpher-copy-current-url)
2214 (define-key map (kbd "a") 'elpher-bookmark-link)
2215 (define-key map (kbd "A") 'elpher-bookmark-current)
2216 (define-key map (kbd "x") 'elpher-unbookmark-link)
2217 (define-key map (kbd "X") 'elpher-unbookmark-current)
2218 (define-key map (kbd "B") 'elpher-bookmarks)
2219 (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
2220 (define-key map (kbd "F") 'elpher-forget-current-certificate)
2221 (define-key map (kbd "v") 'elpher-visit-gemini-numbered-link)
2222 (when (fboundp 'evil-define-key*)
2225 (kbd "TAB") 'elpher-next-link
2226 (kbd "C-") 'elpher-follow-current-link
2227 (kbd "C-t") 'elpher-back
2228 (kbd "u") 'elpher-back
2229 (kbd "-") 'elpher-back
2230 (kbd "^") 'elpher-back
2231 (kbd "U") 'elpher-back-to-start
2232 [mouse-3] 'elpher-back
2233 (kbd "o") 'elpher-go
2234 (kbd "O") 'elpher-go-current
2235 (kbd "r") 'elpher-redraw
2236 (kbd "R") 'elpher-reload
2237 (kbd "T") 'elpher-toggle-tls
2238 (kbd ".") 'elpher-view-raw
2239 (kbd "d") 'elpher-download
2240 (kbd "D") 'elpher-download-current
2241 (kbd "J") 'elpher-jump
2242 (kbd "i") 'elpher-info-link
2243 (kbd "I") 'elpher-info-current
2244 (kbd "c") 'elpher-copy-link-url
2245 (kbd "C") 'elpher-copy-current-url
2246 (kbd "a") 'elpher-bookmark-link
2247 (kbd "A") 'elpher-bookmark-current
2248 (kbd "x") 'elpher-unbookmark-link
2249 (kbd "X") 'elpher-unbookmark-current
2250 (kbd "B") 'elpher-bookmarks
2251 (kbd "S") 'elpher-set-gopher-coding-system
2252 (kbd "F") 'elpher-forget-current-certificate
2253 (kbd "v") 'elpher-visit-gemini-numbered-link))
2255 "Keymap for gopher client.")
2257 (define-derived-mode elpher-mode special-mode "elpher"
2258 "Major mode for elpher, an elisp gopher client.
2260 This mode is automatically enabled by the interactive
2261 functions which initialize the gopher client, namely
2262 `elpher', `elpher-go' and `elpher-bookmarks'."
2263 (setq-local elpher--gemini-page-headings nil)
2264 (setq-local elpher-current-page nil)
2265 (setq-local elpher-history nil)
2266 (setq-local elpher-buffer-name (buffer-name))
2268 (setq-local imenu-create-index-function
2270 elpher--gemini-page-headings)))
2272 (when (fboundp 'evil-set-initial-state)
2273 (evil-set-initial-state 'elpher-mode 'motion))
2276 ;;; Main start procedure
2280 (defun elpher (&optional arg)
2281 "Start elpher with default landing page.
2282 The buffer used for Elpher sessions is determined by the value of
2283 ‘elpher-buffer-name’. If there is already an Elpher session active in
2284 that buffer, Emacs will simply switch to it. Otherwise, a new session
2285 will begin. A numeric prefix ARG (as in ‘\\[universal-argument] 42
2286 \\[execute-extended-command] elpher RET’) switches to the session with
2287 that number, creating it if necessary. A non numeric prefix ARG means
2288 to create a new session. Returns the buffer selected (or created)."
2290 (let* ((name (default-value 'elpher-buffer-name))
2291 (buf (cond ((numberp arg)
2292 (get-buffer-create (format "%s<%d>" name arg)))
2294 (generate-new-buffer name))
2296 (get-buffer-create name)))))
2297 (pop-to-buffer-same-window buf)
2298 (unless (buffer-modified-p)
2300 (elpher-visit-page (elpher-make-start-page))
2301 "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2303 ;;; elpher.el ends here