1 ;;; elpher.el --- A friendly gopher and gemini client -*- lexical-binding:t -*-
3 ;; Copyright (C) 2019 Tim Vaughan
5 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
6 ;; Created: 11 April 2019
8 ;; Keywords: comm gopher
9 ;; Homepage: http://thelambdalab.xyz/elpher
10 ;; Package-Requires: ((emacs "26"))
12 ;; This file is not part of GNU Emacs.
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.
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.
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/>.
29 ;; Elpher aims to provide a practical and friendly gopher and gemini
30 ;; client for GNU Emacs. It supports:
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 ;; - gopher connections using TLS encryption,
40 ;; - the fledgling Gemini protocol,
41 ;; - the greybeard Finger protocol.
43 ;; To launch Elpher, simply use 'M-x elpher'. This will open a start
44 ;; page containing information on key bindings and suggested starting
45 ;; points for your gopher exploration.
47 ;; Full instructions can be found in the Elpher info manual.
49 ;; Elpher is under active development. Any suggestions for
50 ;; improvements are welcome, and can be made on the official
51 ;; project page, gopher://thelambdalab.xyz/1/projects/elpher/.
73 (defconst elpher-version "2.7.9"
74 "Current version of elpher.")
76 (defconst elpher-margin-width 6
77 "Width of left-hand margin used when rendering indicies.")
79 (defconst elpher-type-map
80 '(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
81 ((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
82 ((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
83 ((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
84 ((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
85 ((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
86 ((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
87 ((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
88 ((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
89 ((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
90 ((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
91 ((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
92 ((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
93 (gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
94 (finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
95 (telnet elpher-get-telnet-page nil "tel" elpher-telnet)
96 (other-url elpher-get-other-url-page nil "url" elpher-other-url)
97 ((special bookmarks) elpher-get-bookmarks-page nil "/" elpher-index)
98 ((special start) elpher-get-start-page nil))
99 "Association list from types to getters, renderers, margin codes and index faces.")
102 ;;; Customization group
107 :group 'applications)
109 ;; General appearance and customizations
111 (defcustom elpher-open-urls-with-eww nil
112 "If non-nil, open URL selectors using eww.
113 Otherwise, use the system browser via the BROWSE-URL function."
116 (defcustom elpher-use-header t
117 "If non-nil, display current page information in buffer header."
120 (defcustom elpher-auto-disengage-TLS nil
121 "If non-nil, automatically disengage TLS following an unsuccessful connection.
122 While enabling this may seem convenient, it is also potentially dangerous as it
123 allows switching from an encrypted channel back to plain text without user input."
126 (defcustom elpher-connection-timeout 5
127 "Specifies the number of seconds to wait for a network connection to time out."
130 (defcustom elpher-filter-ansi-from-text nil
131 "If non-nil, filter ANSI escape sequences from text.
132 The default behaviour is to use the ansi-color package to interpret these
136 (defcustom elpher-gemini-TLS-cert-checks nil
137 "If non-nil, verify gemini server TLS certs using the default security level.
138 Otherwise, certificate verification is disabled.
140 This defaults to off because it is standard practice for Gemini servers
141 to use self-signed certificates, meaning that most servers provide what
142 EMACS considers to be an invalid certificate."
145 (defcustom elpher-gemini-max-fill-width 80
146 "Specify the maximum default width (in columns) of text/gemini documents.
147 The actual width used is the minimum of this value and the window width at
148 the time when the text is rendered."
151 (defcustom elpher-gemini-link-string "→ "
152 "Specify the string used to indicate links when rendering gemini maps.
156 (defcustom elpher-gemini-bullet-string "•"
157 "Specify the string used for bullets when rendering gemini maps."
160 (defcustom elpher-bookmarks-file (locate-user-emacs-file "elpher-bookmarks")
161 "Specify the name of the file where elpher bookmarks will be saved."
164 (defcustom elpher-force-ipv4 nil
165 "If non-nil, force elpher to use ipv4 instead of trying an ipv6 address
166 and falling back to an ipv4 address"
169 ;; Face customizations
171 (defgroup elpher-faces nil
172 "Elpher face customizations."
175 (defface elpher-index
176 '((t :inherit font-lock-keyword-face))
177 "Face used for directory type directory records.")
181 "Face used for text type directory records.")
184 '((t :inherit default))
185 "Face used for info type directory records.")
187 (defface elpher-image
188 '((t :inherit font-lock-string-face))
189 "Face used for image type directory records.")
191 (defface elpher-search
192 '((t :inherit warning))
193 "Face used for search type directory records.")
196 '((t :inherit font-lock-comment-face))
197 "Face used for html type directory records.")
199 (defface elpher-gemini
200 '((t :inherit font-lock-regexp-grouping-backslash))
201 "Face used for Gemini type directory records.")
203 (defface elpher-other-url
204 '((t :inherit font-lock-comment-face))
205 "Face used for other URL type links records.")
207 (defface elpher-telnet
208 '((t :inherit font-lock-function-name-face))
209 "Face used for telnet type directory records.")
211 (defface elpher-binary
212 '((t :inherit font-lock-doc-face))
213 "Face used for binary type directory records.")
215 (defface elpher-unknown
216 '((t :inherit error))
217 "Face used for directory records with unknown/unsupported types.")
219 (defface elpher-margin-key
221 "Face used for directory margin key.")
223 (defface elpher-margin-brackets
224 '((t :inherit shadow))
225 "Face used for brackets around directory margin key.")
227 (defface elpher-gemini-heading1
228 '((t :inherit bold :height 1.8))
229 "Face used for gemini heading level 1.")
231 (defface elpher-gemini-heading2
232 '((t :inherit bold :height 1.5))
233 "Face used for gemini heading level 2.")
235 (defface elpher-gemini-heading3
236 '((t :inherit bold :height 1.2))
237 "Face used for gemini heading level 3.")
239 (defface elpher-gemini-preformatted
240 '((t :inherit fixed-pitch))
241 "Face used for pre-formatted gemini text blocks.")
248 ;; An elpher "address" object is either a url object or a symbol.
249 ;; Symbol addresses are "special", corresponding to pages generated
250 ;; dynamically for and by elpher. All others represent pages which
251 ;; rely on content retrieved over the network.
253 (defun elpher-address-from-url (url-string)
254 "Create a ADDRESS object corresponding to the given URL-STRING."
255 (let ((data (match-data))) ; Prevent parsing clobbering match data
257 (let ((url (url-generic-parse-url url-string)))
258 (unless (and (not (url-fullness url)) (url-type url))
259 (setf (url-fullness url) t)
260 (setf (url-filename url)
261 (url-unhex-string (url-filename url)))
262 (unless (url-type url)
263 (setf (url-type url) "gopher"))
264 (when (or (equal "gopher" (url-type url))
265 (equal "gophers" (url-type url)))
267 (unless (url-host url)
268 (setf (url-host url) (url-filename url))
269 (setf (url-filename url) ""))
270 (when (or (equal (url-filename url) "")
271 (equal (url-filename url) "/"))
272 (setf (url-filename url) "/1")))
273 (when (equal "gemini" (url-type url))
275 (if (equal (url-filename url) "")
276 (setf (url-filename url) "/"))))
278 (set-match-data data))))
280 (defun elpher-make-gopher-address (type selector host port &optional tls)
281 "Create an ADDRESS object using gopher directory record attributes.
282 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
283 If the optional attribute TLS is non-nil, the address will be marked as
284 requiring gopher-over-TLS."
286 ((equal type ?i) nil)
287 ((and (equal type ?h)
288 (string-prefix-p "URL:" selector))
289 (elpher-address-from-url (elt (split-string selector "URL:") 1)))
291 (elpher-address-from-url
294 ":" (number-to-string port))))
296 (elpher-address-from-url
297 (concat "gopher" (if tls "s" "")
299 ":" (number-to-string port)
303 (defun elpher-make-special-address (type)
304 "Create an ADDRESS object corresponding to the given special address symbol TYPE."
307 (defun elpher-address-to-url (address)
308 "Get string representation of ADDRESS, or nil if ADDRESS is special."
309 (if (not (elpher-address-special-p address))
310 (url-encode-url (url-recreate-url address))
313 (defun elpher-address-type (address)
314 "Retrieve type of ADDRESS object.
315 This is used to determine how to retrieve and render the document the
316 address refers to, via the table `elpher-type-map'."
317 (if (symbolp address)
318 (list 'special address)
319 (let ((protocol (url-type address)))
320 (cond ((or (equal protocol "gopher")
321 (equal protocol "gophers"))
323 (if (member (url-filename address) '("" "/"))
325 (string-to-char (substring (url-filename address) 1)))))
326 ((equal protocol "gemini")
328 ((equal protocol "telnet")
330 ((equal protocol "finger")
334 (defun elpher-address-protocol (address)
335 "Retrieve the transport protocol for ADDRESS. This is nil for special addresses."
336 (if (symbolp address)
340 (defun elpher-address-filename (address)
341 "Retrieve the filename component of ADDRESS.
342 For gopher addresses this is a combination of the selector type and selector."
343 (if (symbolp address)
345 (url-filename address)))
347 (defun elpher-address-host (address)
348 "Retrieve host from ADDRESS object."
351 (defun elpher-address-user (address)
352 "Retrieve user from ADDRESS object."
355 (defun elpher-address-port (address)
356 "Retrieve port from ADDRESS object.
357 If no address is defined, returns 0. (This is for compatibility with the URL library.)"
358 (if (symbolp address)
362 (defun elpher-address-special-p (address)
363 "Return non-nil if ADDRESS object is special (e.g. start page, bookmarks page)."
366 (defun elpher-address-gopher-p (address)
367 "Return non-nill if ADDRESS object is a gopher address."
368 (and (not (elpher-address-special-p address))
369 (member (elpher-address-protocol address) '("gopher gophers"))))
371 (defun elpher-gopher-address-selector (address)
372 "Retrieve gopher selector from ADDRESS object."
373 (if (member (url-filename address) '("" "/"))
375 (url-unhex-string (substring (url-filename address) 2))))
380 (defvar elpher-content-cache (make-hash-table :test 'equal))
381 (defvar elpher-pos-cache (make-hash-table :test 'equal))
383 (defun elpher-get-cached-content (address)
384 "Retrieve the cached content for ADDRESS, or nil if none exists."
385 (gethash address elpher-content-cache))
387 (defun elpher-cache-content (address content)
388 "Set the content cache for ADDRESS to CONTENT."
389 (puthash address content elpher-content-cache))
391 (defun elpher-get-cached-pos (address)
392 "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
393 (gethash address elpher-pos-cache))
395 (defun elpher-cache-pos (address pos)
396 "Set the cursor position cache for ADDRESS to POS."
397 (puthash address pos elpher-pos-cache))
402 (defun elpher-make-page (display-string address)
403 "Create a page with DISPLAY-STRING and ADDRESS."
404 (list display-string address))
406 (defun elpher-page-display-string (page)
407 "Retrieve the display string corresponding to PAGE."
410 (defun elpher-page-address (page)
411 "Retrieve the address corresponding to PAGE."
414 (defun elpher-page-set-address (page new-address)
415 "Set the address corresponding to PAGE to NEW-ADDRESS."
416 (setcar (cdr page) new-address))
418 (defvar elpher-current-page nil)
419 (defvar elpher-history nil)
421 (defun elpher-visit-page (page &optional renderer no-history)
422 "Visit PAGE using its own renderer or RENDERER, if non-nil.
423 Additionally, push PAGE onto the stack of previously-visited pages,
424 unless NO-HISTORY is non-nil."
426 (elpher-process-cleanup)
427 (unless (or no-history
428 (equal (elpher-page-address elpher-current-page)
429 (elpher-page-address page)))
430 (push elpher-current-page elpher-history))
431 (setq elpher-current-page page)
432 (let* ((address (elpher-page-address page))
433 (type (elpher-address-type address))
434 (type-record (cdr (assoc type elpher-type-map))))
436 (funcall (car type-record)
440 (elpher-visit-previous-page)
442 (`(gopher ,type-char)
443 (error "Unsupported gopher selector type '%c' for '%s'"
444 type-char (elpher-address-to-url address)))
446 (error "Unsupported address type '%S' for '%s'"
447 other (elpher-address-to-url address)))))))
449 (defun elpher-visit-previous-page ()
450 "Visit the previous page in the history."
451 (let ((previous-page (pop elpher-history)))
453 (elpher-visit-page previous-page nil t)
454 (error "No previous page"))))
456 (defun elpher-reload-current-page ()
457 "Reload the current page, discarding any existing cached content."
458 (elpher-cache-content (elpher-page-address elpher-current-page) nil)
459 (elpher-visit-page elpher-current-page))
461 (defun elpher-save-pos ()
462 "Save the current position of point to the current page."
463 (when elpher-current-page
464 (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
466 (defun elpher-restore-pos ()
467 "Restore the position of point to that cached in the current page."
468 (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
471 (goto-char (point-min)))))
474 ;;; Buffer preparation
477 (defun elpher-update-header ()
478 "If `elpher-use-header' is true, display current page info in window header."
479 (if elpher-use-header
480 (let* ((display-string (elpher-page-display-string elpher-current-page))
481 (address (elpher-page-address elpher-current-page))
482 (tls-string (if (and (not (elpher-address-special-p address))
483 (member (elpher-address-protocol address)
484 '("gophers" "gemini")))
487 (header (concat display-string
488 (propertize tls-string 'face 'bold))))
489 (setq header-line-format header))))
491 (defmacro elpher-with-clean-buffer (&rest args)
492 "Evaluate ARGS with a clean *elpher* buffer as current."
493 (list 'with-current-buffer "*elpher*"
495 (append (list 'let '((inhibit-read-only t))
496 '(setq-local network-security-level
497 (default-value 'network-security-level))
499 '(elpher-update-header))
506 (defvar elpher-user-coding-system nil
507 "User-specified coding system to use for decoding text responses.")
509 (defun elpher-decode (string)
510 "Decode STRING using autodetected or user-specified coding system."
511 (decode-coding-string string
512 (if elpher-user-coding-system
513 elpher-user-coding-system
514 (detect-coding-string string t))))
516 (defun elpher-preprocess-text-response (string)
517 "Preprocess text selector response contained in STRING.
518 This involes decoding the character representation, and clearing
519 away CRs and any terminating period."
520 (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
521 (replace-regexp-in-string "\r" "" string))))
524 ;;; Network error reporting
527 (defun elpher-network-error (address error)
528 "Display ERROR message following unsuccessful negotiation with ADDRESS.
529 ERROR can be either an error object or a string."
530 (elpher-with-clean-buffer
531 (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
532 "When attempting to retrieve " (elpher-address-to-url address) ":\n"
533 (if (stringp error) error (error-message-string error)) "\n"
534 (propertize "\n----------------\n\n" 'face 'error)
535 "Press 'u' to return to the previous page.")))
538 ;;; Gopher selector retrieval
541 (defvar elpher-network-timer nil
542 "Timer used for network connections.")
544 (defun elpher-process-cleanup ()
545 "Immediately shut down any extant elpher process and timers."
546 (let ((p (get-process "elpher-process")))
547 (if p (delete-process p)))
548 (if (timerp elpher-network-timer)
549 (cancel-timer elpher-network-timer)))
551 (defvar elpher-use-tls nil
552 "If non-nil, use TLS to communicate with gopher servers.")
554 (defun elpher-get-selector (address renderer &optional force-ipv4)
555 "Retrieve selector specified by ADDRESS, then render it using RENDERER.
556 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
558 (when (equal (elpher-address-protocol address) "gophers")
559 (if (gnutls-available-p)
560 (when (not elpher-use-tls)
561 (setq elpher-use-tls t)
562 (message "Engaging TLS gopher mode."))
563 (error "Cannot retrieve TLS gopher selector: GnuTLS not available")))
564 (unless (< (elpher-address-port address) 65536)
565 (error "Cannot retrieve gopher selector: port number > 65536"))
567 (let* ((kill-buffer-query-functions nil)
568 (gnutls-verify-error nil) ; We use the NSM for verification
569 (port (elpher-address-port address))
570 (host (elpher-address-host address))
571 (selector-string-parts nil)
574 (proc (open-network-stream "elpher-process"
576 (if force-ipv4 (dns-query host) host)
577 (if (> port 0) port 70)
578 :type (if elpher-use-tls 'tls 'plain)
580 (timer (run-at-time elpher-connection-timeout
583 (pcase (process-status proc)
585 (if (and (not (equal (elpher-address-protocol address)
588 (or elpher-auto-disengage-TLS
589 (yes-or-no-p "Could not establish encrypted connection. Disable TLS mode?")))
591 (message "Disabling TLS mode.")
592 (setq elpher-use-tls nil)
593 (elpher-get-selector address renderer elpher-force-ipv4))
594 (elpher-network-error address "Could not establish encrypted connection")))
596 (elpher-process-cleanup)
598 (message "Connection timed out. Retrying with IPv4 address.")
599 (elpher-get-selector address renderer t))))))))
600 (setq elpher-network-timer timer)
601 (set-process-coding-system proc 'binary)
602 (set-process-filter proc
603 (lambda (_proc string)
607 (setq bytes-received (+ bytes-received (length string)))
608 (let ((new-hkbytes-received (/ bytes-received 102400)))
609 (when (> new-hkbytes-received hkbytes-received)
610 (setq hkbytes-received new-hkbytes-received)
611 (with-current-buffer "*elpher*"
612 (let ((inhibit-read-only t))
613 (goto-char (point-min))
614 (beginning-of-line 2)
615 (delete-region (point) (point-max))
617 (number-to-string (/ hkbytes-received 10.0))
619 (setq selector-string-parts
620 (cons string selector-string-parts))))
621 (set-process-sentinel proc
622 (lambda (_proc event)
623 (condition-case the-error
625 ((string-prefix-p "deleted" event))
626 ((string-prefix-p "open" event)
627 (let ((inhibit-eol-conversion t))
630 (concat (elpher-gopher-address-selector address)
636 (funcall renderer (apply #'concat
637 (reverse selector-string-parts)))
638 (elpher-restore-pos)))
640 (elpher-network-error address the-error))))))
642 (error "Error initiating connection to server"))))
644 (defun elpher-get-gopher-page (renderer)
645 "Getter function for gopher pages.
646 The RENDERER procedure is used to display the contents of the page
647 once they are retrieved from the gopher server."
648 (let* ((address (elpher-page-address elpher-current-page))
649 (content (elpher-get-cached-content address)))
650 (if (and content (funcall renderer nil))
651 (elpher-with-clean-buffer
653 (elpher-restore-pos))
654 (elpher-with-clean-buffer
655 (insert "LOADING... (use 'u' to cancel)\n"))
656 (condition-case the-error
657 (elpher-get-selector address renderer elpher-force-ipv4)
659 (elpher-network-error address the-error))))))
663 (defun elpher-insert-index (string)
664 "Insert the index corresponding to STRING into the current buffer."
665 ;; Should be able to split directly on CRLF, but some non-conformant
666 ;; LF-only servers sadly exist, hence the following.
667 (let ((str-processed (elpher-preprocess-text-response string)))
668 (dolist (line (split-string str-processed "\n"))
670 (unless (= (length line) 0)
671 (let* ((type (elt line 0))
672 (fields (split-string (substring line 1) "\t"))
673 (display-string (elt fields 0))
674 (selector (elt fields 1))
675 (host (elt fields 2))
676 (port (if (elt fields 3)
677 (string-to-number (elt fields 3))
679 (address (elpher-make-gopher-address type selector host port)))
680 (elpher-insert-index-record display-string address)))))))
682 (defun elpher-insert-margin (&optional type-name)
683 "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
686 (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
688 (propertize "[" 'face 'elpher-margin-brackets)
689 (propertize type-name 'face 'elpher-margin-key)
690 (propertize "]" 'face 'elpher-margin-brackets))))
692 (insert (make-string elpher-margin-width ?\s))))
694 (defun elpher--page-button-help (_window buffer pos)
695 "Function called by Emacs to generate mouse-over text.
696 The arguments specify the BUFFER and the POS within the buffer of the item
697 for which help is required. The function returns the help to be
698 displayed. The _WINDOW argument is currently unused."
699 (with-current-buffer buffer
700 (let ((button (button-at pos)))
702 (let* ((page (button-get button 'elpher-page))
703 (address (elpher-page-address page)))
704 (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
706 (url-recreate-url address))))))))
708 (defun elpher-insert-index-record (display-string &optional address)
709 "Function to insert an index record into the current buffer.
710 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
711 If ADDRESS is not supplied or nil the record is rendered as an
713 (let* ((type (if address (elpher-address-type address) nil))
714 (type-map-entry (cdr (assoc type elpher-type-map))))
716 (let* ((margin-code (elt type-map-entry 2))
717 (face (elt type-map-entry 3))
718 (filtered-display-string (ansi-color-filter-apply display-string))
719 (page (elpher-make-page filtered-display-string address)))
720 (elpher-insert-margin margin-code)
721 (insert-text-button filtered-display-string
724 'action #'elpher-click-link
726 'help-echo #'elpher--page-button-help))
729 (elpher-insert-margin)
730 (let ((propertized-display-string
731 (propertize display-string 'face 'elpher-info)))
732 (insert (elpher-process-text-for-display propertized-display-string))))
733 (`(gopher ,selector-type) ;; Unknown
734 (elpher-insert-margin (concat (char-to-string selector-type) "?"))
735 (insert (propertize display-string
736 'face 'elpher-unknown)))))
739 (defun elpher-click-link (button)
740 "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
741 (let ((page (button-get button 'elpher-page)))
742 (elpher-visit-page page)))
744 (defun elpher-render-index (data &optional _mime-type-string)
745 "Render DATA as an index. MIME-TYPE-STRING is unused."
746 (elpher-with-clean-buffer
749 (elpher-insert-index data)
750 (elpher-cache-content (elpher-page-address elpher-current-page)
755 (defconst elpher-url-regex
756 "\\([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\-_~?/@|#]\\)?\\)?"
757 "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
759 (defun elpher-buttonify-urls (string)
760 "Turn substrings which look like urls in STRING into clickable buttons."
763 (goto-char (point-min))
764 (while (re-search-forward elpher-url-regex nil t)
765 (let ((page (elpher-make-page (substring-no-properties (match-string 0))
766 (elpher-address-from-url (match-string 0)))))
767 (make-text-button (match-beginning 0)
770 'action #'elpher-click-link
772 'help-echo #'elpher--page-button-help
776 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
777 "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
779 (defun elpher-process-text-for-display (string)
780 "Perform any desired processing of STRING prior to display as text.
781 Currently includes buttonifying URLs and processing ANSI escape codes."
782 (elpher-buttonify-urls (if elpher-filter-ansi-from-text
783 (ansi-color-filter-apply string)
784 (ansi-color-apply string))))
786 (defun elpher-render-text (data &optional _mime-type-string)
787 "Render DATA as text. MIME-TYPE-STRING is unused."
788 (elpher-with-clean-buffer
791 (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
792 (elpher-cache-content
793 (elpher-page-address elpher-current-page)
798 (defun elpher-render-image (data &optional _mime-type-string)
799 "Display DATA as image. MIME-TYPE-STRING is unused."
802 (if (display-images-p)
804 (let ((image (create-image
807 (elpher-with-clean-buffer
809 (elpher-restore-pos))))
810 (elpher-render-download data))))
812 ;; Search retrieval and rendering
814 (defun elpher-get-gopher-query-page (renderer)
815 "Getter for gopher addresses requiring input.
816 The response is rendered using the rendering function RENDERER."
817 (let* ((address (elpher-page-address elpher-current-page))
818 (content (elpher-get-cached-content address))
820 (if (and content (funcall renderer nil))
821 (elpher-with-clean-buffer
824 (message "Displaying cached search results. Reload to perform a new search."))
826 (let* ((query-string (read-string "Query: "))
827 (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
828 (search-address (elpher-make-gopher-address ?1
830 (elpher-address-host address)
831 (elpher-address-port address)
832 (equal (elpher-address-type address) "gophers"))))
835 (elpher-with-clean-buffer
836 (insert "LOADING RESULTS... (use 'u' to cancel)"))
837 (elpher-get-selector search-address renderer elpher-force-ipv4))
839 (elpher-visit-previous-page))))))
841 ;; Raw server response rendering
843 (defun elpher-render-raw (data &optional mime-type-string)
844 "Display raw DATA in buffer. MIME-TYPE-STRING is also displayed if provided."
847 (elpher-with-clean-buffer
848 (when mime-type-string
849 (insert "MIME type specified by server: '" mime-type-string "'\n"))
851 (goto-char (point-min)))
852 (message "Displaying raw server response. Reload or redraw to return to standard view.")))
854 ;; File save "rendering"
856 (defun elpher-render-download (data &optional _mime-type-string)
857 "Save DATA to file. MIME-TYPE-STRING is unused."
860 (let* ((address (elpher-page-address elpher-current-page))
861 (selector (if (elpher-address-gopher-p address)
862 (elpher-gopher-address-selector address)
863 (elpher-address-filename address))))
864 (elpher-visit-previous-page) ; Do first in case of non-local exits.
865 (let* ((filename-proposal (file-name-nondirectory selector))
866 (filename (read-file-name "Download complete. Save file as: "
868 (if (> (length filename-proposal) 0)
871 (let ((coding-system-for-write 'binary))
872 (with-temp-file filename
874 (message (format "Saved to file %s." filename))))))
878 (defun elpher-render-html (data &optional _mime-type-string)
879 "Render DATA as HTML using shr. MIME-TYPE-STRING is unused."
880 (elpher-with-clean-buffer
883 (let ((dom (with-temp-buffer
885 (libxml-parse-html-region (point-min) (point-max)))))
886 (shr-insert-document dom)))))
888 ;; Gemini page retrieval
890 (defvar elpher-gemini-redirect-chain)
892 (defun elpher-get-gemini-response (address renderer &optional force-ipv4)
893 "Retrieve gemini ADDRESS, then render using RENDERER.
894 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
896 (unless elpher-gemini-TLS-cert-checks
897 (setq-local network-security-level 'low))
898 (if (not (gnutls-available-p))
899 (error "Cannot establish gemini connection: GnuTLS not available")
900 (unless (< (elpher-address-port address) 65536)
901 (error "Cannot establish gemini connection: port number > 65536"))
902 (defvar gnutls-verify-error)
904 (let* ((kill-buffer-query-functions nil)
905 (gnutls-verify-error nil) ; We use the NSM for verification
906 (port (elpher-address-port address))
907 (host (elpher-address-host address))
908 (response-string-parts nil)
911 (proc (open-network-stream "elpher-process"
913 (if force-ipv4 (dns-query host) host)
914 (if (> port 0) port 1965)
917 (timer (run-at-time elpher-connection-timeout nil
919 (elpher-process-cleanup)
921 ; Try again with IPv4
922 (message "Connection timed out. Retrying with IPv4.")
923 (elpher-get-gemini-response address renderer t))))))
924 (setq elpher-network-timer timer)
925 (set-process-coding-system proc 'binary)
926 (set-process-filter proc
927 (lambda (_proc string)
931 (setq bytes-received (+ bytes-received (length string)))
932 (let ((new-hkbytes-received (/ bytes-received 102400)))
933 (when (> new-hkbytes-received hkbytes-received)
934 (setq hkbytes-received new-hkbytes-received)
935 (with-current-buffer "*elpher*"
936 (let ((inhibit-read-only t))
937 (goto-char (point-min))
938 (beginning-of-line 2)
939 (delete-region (point) (point-max))
941 (number-to-string (/ hkbytes-received 10.0))
943 (setq response-string-parts
944 (cons string response-string-parts))))
945 (set-process-sentinel proc
947 (condition-case the-error
949 ((string-prefix-p "open" event) ; request URL
950 (let ((inhibit-eol-conversion t))
953 (concat (elpher-address-to-url address)
955 ((string-prefix-p "deleted" event)) ; do nothing
956 ((and (not response-string-parts)
958 ; Try again with IPv4
959 (message "Connection failed. Retrying with IPv4.")
961 (elpher-get-gemini-response address renderer t))
963 (funcall #'elpher-process-gemini-response
964 (apply #'concat (reverse response-string-parts))
966 (elpher-restore-pos)))
968 (elpher-network-error address the-error))))))
970 (error "Error initiating connection to server")))))
972 (defun elpher-parse-gemini-response (response)
973 "Parse the RESPONSE string and return a list of components.
974 The list is of the form (code meta body). A response of nil implies
975 that the response was malformed."
976 (let ((header-end-idx (string-match "\r\n" response)))
978 (let ((header (string-trim (substring response 0 header-end-idx)))
979 (body (substring response (+ header-end-idx 2))))
980 (if (>= (length header) 2)
981 (let ((code (substring header 0 2))
982 (meta (string-trim (substring header 2))))
983 (list code meta body))
984 (error "Malformed response: No response status found in header %s" header)))
985 (error "Malformed response: No CRLF-delimited header found in response %s" response))))
987 (defun elpher-process-gemini-response (response-string renderer)
988 "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
989 (let ((response-components (elpher-parse-gemini-response response-string)))
990 (let ((response-code (elt response-components 0))
991 (response-meta (elt response-components 1))
992 (response-body (elt response-components 2)))
993 (pcase (elt response-code 0)
995 (elpher-with-clean-buffer
996 (insert "Gemini server is requesting input."))
997 (let* ((query-string (read-string (concat response-meta ": ")))
998 (url (elpher-address-to-url (elpher-page-address elpher-current-page)))
999 (query-address (elpher-address-from-url (concat url "?" query-string))))
1000 (elpher-get-gemini-response query-address renderer)))
1001 (?2 ; Normal response
1002 (funcall renderer response-body response-meta))
1004 (message "Following redirect to %s" response-meta)
1005 (if (>= (length elpher-gemini-redirect-chain) 5)
1006 (error "More than 5 consecutive redirects followed"))
1007 (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1008 (if (member redirect-address elpher-gemini-redirect-chain)
1009 (error "Redirect loop detected"))
1010 (if (not (string= (elpher-address-protocol redirect-address)
1012 (error "Server tried to automatically redirect to non-gemini URL: %s"
1014 (elpher-page-set-address elpher-current-page redirect-address)
1015 (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1016 (elpher-get-gemini-response redirect-address renderer)))
1017 (?4 ; Temporary failure
1018 (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1019 response-code response-meta))
1020 (?5 ; Permanent failure
1021 (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1022 response-code response-meta))
1023 (?6 ; Client certificate required
1024 (error "Gemini server requires client certificate (unsupported at this time)"))
1026 (error "Gemini server response unknown: %s %s"
1027 response-code response-meta))))))
1029 (defun elpher-get-gemini-page (renderer)
1030 "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1031 (let* ((address (elpher-page-address elpher-current-page))
1032 (content (elpher-get-cached-content address)))
1033 (condition-case the-error
1034 (if (and content (funcall renderer nil))
1035 (elpher-with-clean-buffer
1037 (elpher-restore-pos))
1038 (elpher-with-clean-buffer
1039 (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1040 (setq elpher-gemini-redirect-chain nil)
1041 (elpher-get-gemini-response address renderer))
1043 (elpher-network-error address the-error)))))
1046 (defun elpher-render-gemini (body &optional mime-type-string)
1047 "Render gemini response BODY with rendering MIME-TYPE-STRING."
1050 (let* ((mime-type-string* (if (or (not mime-type-string)
1051 (string-empty-p mime-type-string))
1052 "text/gemini; charset=utf-8"
1054 (mime-type-split (split-string mime-type-string* ";" t))
1055 (mime-type (string-trim (car mime-type-split)))
1056 (parameters (mapcar (lambda (s)
1057 (let ((key-val (split-string s "=")))
1058 (list (downcase (string-trim (car key-val)))
1059 (downcase (string-trim (cadr key-val))))))
1060 (cdr mime-type-split))))
1061 (when (string-prefix-p "text/" mime-type)
1062 (setq body (decode-coding-string
1064 (if (assoc "charset" parameters)
1065 (intern (cadr (assoc "charset" parameters)))
1067 (setq body (replace-regexp-in-string "\r" "" body)))
1069 ((or "text/gemini" "")
1070 (elpher-render-gemini-map body parameters))
1072 (elpher-render-html body))
1073 ((pred (string-prefix-p "text/"))
1074 (elpher-render-gemini-plain-text body parameters))
1075 ((pred (string-prefix-p "image/"))
1076 (elpher-render-image body))
1078 (elpher-render-download body))))))
1080 (defun elpher-gemini-get-link-url (link-line)
1081 "Extract the url portion of LINK-LINE, a gemini map file link line.
1082 Returns nil in the event that the contents of the line following the
1083 => prefix are empty."
1084 (let ((l (split-string (substring link-line 2))))
1086 (string-trim (elt l 0))
1089 (defun elpher-gemini-get-link-display-string (link-line)
1090 "Extract the display string portion of LINK-LINE, a gemini map file link line.
1091 Returns the url portion in the event that the display-string portion is empty."
1092 (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1093 (idx (string-match "[ \t]" rest)))
1094 (string-trim (if idx
1095 (substring rest (+ idx 1))
1098 (defun elpher-collapse-dot-sequences (filename)
1099 "Collapse dot sequences in FILENAME.
1100 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1101 (let* ((path (split-string filename "/"))
1102 (path-reversed-normalized
1103 (seq-reduce (lambda (a b)
1104 (cond ((and a (equal b "..") (cdr a)))
1105 ((and (not a) (equal b "..")) a) ;leading .. are dropped
1109 (string-join (reverse path-reversed-normalized) "/")))
1111 (defun elpher-address-from-gemini-url (url)
1112 "Extract address from URL with defaults as per gemini map files."
1113 (let ((address (url-generic-parse-url url)))
1114 (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1115 (setf (url-fullness address) t)
1116 (if (url-host address) ;if there is an explicit host, filenames are absolute
1117 (if (string-empty-p (url-filename address))
1118 (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1119 (setf (url-host address) (url-host (elpher-page-address elpher-current-page)))
1120 (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1121 (setf (url-filename address)
1122 (concat (file-name-directory
1123 (url-filename (elpher-page-address elpher-current-page)))
1124 (url-filename address)))))
1125 (unless (url-type address)
1126 (setf (url-type address) "gemini"))
1127 (if (equal (url-type address) "gemini")
1128 (setf (url-filename address)
1129 (elpher-collapse-dot-sequences (url-filename address)))))
1132 (defun elpher-gemini-insert-link (link-line)
1133 "Insert link described by LINK-LINE into a text/gemini document."
1134 (let* ((url (elpher-gemini-get-link-url link-line))
1135 (display-string (elpher-gemini-get-link-display-string link-line))
1136 (address (elpher-address-from-gemini-url url))
1137 (type (if address (elpher-address-type address) nil))
1138 (type-map-entry (cdr (assoc type elpher-type-map))))
1139 (when display-string
1140 (insert elpher-gemini-link-string)
1142 (let* ((face (elt type-map-entry 3))
1143 (filtered-display-string (ansi-color-filter-apply display-string))
1144 (page (elpher-make-page filtered-display-string address)))
1145 (insert-text-button filtered-display-string
1148 'action #'elpher-click-link
1150 'help-echo #'elpher--page-button-help))
1151 (insert (propertize display-string 'face 'elpher-unknown)))
1154 (defun elpher-gemini-insert-header (header-line)
1155 "Insert header described by HEADER-LINE into a text/gemini document.
1156 The gemini map file line describing the header is given
1158 (when (string-match "^\\(#+\\)[ \t]*" header-line)
1159 (let ((level (length (match-string 1 header-line)))
1160 (header (substring header-line (match-end 0))))
1161 (unless (display-graphic-p)
1162 (insert (make-string level ?#) " "))
1163 (insert (propertize header 'face
1165 (1 'elpher-gemini-heading1)
1166 (2 'elpher-gemini-heading2)
1167 (3 'elpher-gemini-heading3)
1171 (defun elpher-gemini-insert-text (text-line)
1172 "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1173 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1174 width defined by elpher-gemini-max-fill-width."
1175 (string-match "\\(^[ \t]*\\)\\(\*[ \t]\\)?" text-line)
1176 (let* ((processed-text-line (if (match-string 2 text-line)
1178 (replace-regexp-in-string "\*"
1179 elpher-gemini-bullet-string
1180 (match-string 0 text-line))
1181 (substring text-line (match-end 0)))
1183 (fill-prefix (if (match-string 1 text-line)
1184 (replace-regexp-in-string "\*" " " (match-string 0 text-line))
1186 (insert (elpher-process-text-for-display processed-text-line))
1189 (defun elpher-render-gemini-map (data _parameters)
1190 "Render DATA as a gemini map file, PARAMETERS is currently unused."
1191 (elpher-with-clean-buffer
1192 (let ((preformatted nil))
1194 (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1195 (dolist (line (split-string data "\n"))
1197 ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1198 (preformatted (insert (elpher-process-text-for-display
1199 (propertize line 'face 'elpher-gemini-preformatted))
1201 ((string-prefix-p "=>" line) (elpher-gemini-insert-link line))
1202 ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1203 (t (elpher-gemini-insert-text line)))))
1204 (elpher-cache-content
1205 (elpher-page-address elpher-current-page)
1208 (defun elpher-render-gemini-plain-text (data _parameters)
1209 "Render DATA as plain text file. PARAMETERS is currently unused."
1210 (elpher-with-clean-buffer
1211 (insert (elpher-process-text-for-display data))
1212 (elpher-cache-content
1213 (elpher-page-address elpher-current-page)
1216 ;; Finger page connection
1218 (defun elpher-get-finger-page (renderer &optional force-ipv4)
1219 "Opens a finger connection to the current page address.
1220 The result is rendered using RENDERER. When the optional argument
1221 FORCE-IPV4 is non-nil, the IPv4 address returned by a DNS lookup will
1222 be used explicitly in making the connection."
1223 (let* ((address (elpher-page-address elpher-current-page))
1224 (content (elpher-get-cached-content address)))
1225 (if (and content (funcall renderer nil))
1226 (elpher-with-clean-buffer
1228 (elpher-restore-pos))
1229 (elpher-with-clean-buffer
1230 (insert "LOADING... (use 'u' to cancel)\n"))
1231 (condition-case the-error
1232 (let* ((kill-buffer-query-functions nil)
1233 (user (let ((filename (elpher-address-filename address)))
1234 (if (> (length filename) 1)
1235 (substring filename 1)
1236 (elpher-address-user address))))
1237 (port (let ((given-port (elpher-address-port address)))
1238 (if (> given-port 0) given-port 79)))
1239 (host (elpher-address-host address))
1240 (selector-string-parts nil)
1241 (proc (open-network-stream "elpher-process"
1243 (if force-ipv4 (dns-query host) host)
1247 (timer (run-at-time elpher-connection-timeout
1250 (pcase (process-status proc)
1252 (elpher-process-cleanup)
1254 (message "Connection timed out. Retrying with IPv4 address.")
1255 (elpher-get-finger-page renderer t))))))))
1256 (setq elpher-network-timer timer)
1257 (set-process-coding-system proc 'binary)
1258 (set-process-filter proc
1259 (lambda (_proc string)
1261 (cancel-timer timer)
1263 (setq selector-string-parts
1264 (cons string selector-string-parts))))
1265 (set-process-sentinel proc
1266 (lambda (_proc event)
1267 (condition-case _the-error
1269 ((string-prefix-p "deleted" event))
1270 ((string-prefix-p "open" event)
1271 (let ((inhibit-eol-conversion t))
1272 (process-send-string
1274 (concat user "\r\n"))))
1277 (cancel-timer timer)
1279 (funcall renderer (apply #'concat
1280 (reverse selector-string-parts)))
1281 (elpher-restore-pos)))))))
1283 (elpher-network-error address the-error))))))
1286 ;; Other URL page opening
1288 (defun elpher-get-other-url-page (renderer)
1289 "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1291 (elpher-visit-previous-page)
1292 (error "Command not supported for general URLs"))
1293 (let* ((address (elpher-page-address elpher-current-page))
1294 (url (elpher-address-to-url address)))
1296 (elpher-visit-previous-page) ; Do first in case of non-local exits.
1297 (message "Opening URL...")
1298 (if elpher-open-urls-with-eww
1300 (browse-url url)))))
1302 ;; Telnet page connection
1304 (defun elpher-get-telnet-page (renderer)
1305 "Opens a telnet connection to the current page address (RENDERER must be nil)."
1307 (elpher-visit-previous-page)
1308 (error "Command not supported for telnet URLs"))
1309 (let* ((address (elpher-page-address elpher-current-page))
1310 (host (elpher-address-host address))
1311 (port (elpher-address-port address)))
1312 (elpher-visit-previous-page)
1317 ;; Start page page retrieval
1319 (defun elpher-get-start-page (renderer)
1320 "Getter which displays the start page (RENDERER must be nil)."
1322 (elpher-visit-previous-page)
1323 (error "Command not supported for start page"))
1324 (elpher-with-clean-buffer
1325 (insert " --------------------------------------------\n"
1326 " Elpher Gopher and Gemini Client \n"
1327 " version " elpher-version "\n"
1328 " --------------------------------------------\n"
1330 "Default bindings:\n"
1332 " - TAB/Shift-TAB: next/prev item on current page\n"
1333 " - RET/mouse-1: open item under cursor\n"
1334 " - m: select an item on current page by name (autocompletes)\n"
1335 " - u/mouse-3/U: return to previous page or to the start page\n"
1336 " - o/O: visit different selector or the root menu of the current server\n"
1337 " - g: go to a particular address (gopher, gemini, finger)\n"
1338 " - d/D: download item under cursor or current page\n"
1339 " - i/I: info on item under cursor or current page\n"
1340 " - c/C: copy URL representation of item under cursor or current page\n"
1341 " - a/A: bookmark the item under cursor or current page\n"
1342 " - x/X: remove bookmark for item under cursor or current page\n"
1343 " - B: visit the bookmarks page\n"
1344 " - r: redraw current page (using cached contents if available)\n"
1345 " - R: reload current page (regenerates cache)\n"
1346 " - S: set character coding system for gopher (default is to autodetect)\n"
1347 " - T: toggle TLS gopher mode\n"
1348 " - .: display the raw server response for the current page\n"
1350 "Start your exploration of gopher space and gemini:\n")
1351 (elpher-insert-index-record "Floodgap Systems Gopher Server"
1352 (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1353 (elpher-insert-index-record "Project Gemini home page"
1354 (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1356 "Alternatively, select a search engine and enter some search terms:\n")
1357 (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1358 (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1359 (elpher-insert-index-record "Gemini Search Engine (GUS)"
1360 (elpher-address-from-url "gemini://gus.guru/search"))
1362 "This page contains your bookmarked sites (also visit with B):\n")
1363 (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1365 "For Elpher release news or to leave feedback, visit:\n")
1366 (elpher-insert-index-record "The Elpher Project Page"
1367 (elpher-make-gopher-address ?1
1373 (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1374 (insert-text-button "Elpher info manual"
1380 'help-echo help-string))
1381 (insert " for the full documentation. **\n")
1383 (concat " (This should be available if you have installed Elpher using\n"
1384 " MELPA. Otherwise you will have to install the manual yourself.)\n")
1386 (elpher-restore-pos)))
1388 ;; Bookmarks page page retrieval
1390 (defun elpher-get-bookmarks-page (renderer)
1391 "Getter to load and display the current bookmark list (RENDERER must be nil)."
1393 (elpher-visit-previous-page)
1394 (error "Command not supported for bookmarks page"))
1395 (elpher-with-clean-buffer
1396 (insert "---- Bookmark list ----\n\n")
1397 (let ((bookmarks (elpher-load-bookmarks)))
1399 (dolist (bookmark bookmarks)
1400 (let ((display-string (elpher-bookmark-display-string bookmark))
1401 (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1402 (elpher-insert-index-record display-string address)))
1403 (insert "No bookmarks found.\n")))
1404 (insert "\n-----------------------\n"
1406 "- u: return to previous page\n"
1407 "- x: delete selected bookmark\n"
1408 "- a: rename selected bookmark\n"
1410 "Bookmarks are stored in the file ")
1411 (let ((filename elpher-bookmarks-file)
1412 (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1413 (insert-text-button filename
1417 (find-file filename))
1419 'help-echo help-string))
1421 (elpher-restore-pos)))
1427 (defun elpher-make-bookmark (display-string url)
1428 "Make an elpher bookmark.
1429 DISPLAY-STRING determines how the bookmark will appear in the
1430 bookmark list, while URL is the url of the entry."
1431 (list display-string url))
1433 (defun elpher-bookmark-display-string (bookmark)
1434 "Get the display string of BOOKMARK."
1437 (defun elpher-set-bookmark-display-string (bookmark display-string)
1438 "Set the display string of BOOKMARK to DISPLAY-STRING."
1439 (setcar bookmark display-string))
1441 (defun elpher-bookmark-url (bookmark)
1442 "Get the address for BOOKMARK."
1445 (defun elpher-save-bookmarks (bookmarks)
1446 "Record the bookmark list BOOKMARKS to the user's bookmark file.
1447 Beware that this completely replaces the existing contents of the file."
1448 (with-temp-file elpher-bookmarks-file
1450 (insert "; Elpher bookmarks file\n\n"
1451 "; Bookmarks are stored as a list of (label URL) items.\n"
1452 "; Feel free to edit by hand, but take care to ensure\n"
1453 "; the list structure remains intact.\n\n")
1454 (pp bookmarks (current-buffer))))
1456 (defun elpher-load-bookmarks ()
1457 "Get the list of bookmarks from the users's bookmark file."
1461 (insert-file-contents elpher-bookmarks-file)
1462 (goto-char (point-min))
1463 (read (current-buffer))))))
1464 (if (and bookmarks (listp (cadar bookmarks)))
1466 (message "Reading old bookmark file. (Will be updated on write.)")
1467 (mapcar (lambda (old-bm)
1469 (elpher-address-to-url (apply #'elpher-make-gopher-address
1474 (defun elpher-add-address-bookmark (address display-string)
1475 "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1476 If ADDRESS is already bookmarked, update the label only."
1477 (let ((bookmarks (elpher-load-bookmarks))
1478 (url (elpher-address-to-url address)))
1479 (let ((existing-bookmark (rassoc (list url) bookmarks)))
1480 (if existing-bookmark
1481 (elpher-set-bookmark-display-string existing-bookmark display-string)
1482 (push (elpher-make-bookmark display-string url) bookmarks)))
1483 (elpher-save-bookmarks bookmarks)))
1485 (defun elpher-remove-address-bookmark (address)
1486 "Remove any bookmark to ADDRESS."
1487 (let ((url (elpher-address-to-url address)))
1488 (elpher-save-bookmarks
1489 (seq-filter (lambda (bookmark)
1490 (not (equal (elpher-bookmark-url bookmark) url)))
1491 (elpher-load-bookmarks)))))
1493 ;;; Interactive procedures
1496 (defun elpher-next-link ()
1497 "Move point to the next link on the current page."
1501 (defun elpher-prev-link ()
1502 "Move point to the previous link on the current page."
1504 (backward-button 1))
1506 (defun elpher-follow-current-link ()
1507 "Open the link or url at point."
1511 (defun elpher-go (host-or-url)
1512 "Go to a particular gopher site HOST-OR-URL.
1513 When run interactively HOST-OR-URL is read from the minibuffer."
1514 (interactive "sGopher or Gemini URL: ")
1515 (let ((page (elpher-make-page host-or-url
1516 (elpher-address-from-url host-or-url))))
1517 (switch-to-buffer "*elpher*")
1518 (elpher-visit-page page)
1521 (defun elpher-go-current ()
1522 "Go to a particular site read from the minibuffer, initialized with the current URL."
1524 (let ((address (elpher-page-address elpher-current-page)))
1525 (if (elpher-address-special-p address)
1526 (error "Command invalid for this page")
1527 (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1528 (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1530 (defun elpher-redraw ()
1531 "Redraw current page."
1533 (elpher-visit-page elpher-current-page))
1535 (defun elpher-reload ()
1536 "Reload current page."
1538 (elpher-reload-current-page))
1540 (defun elpher-toggle-tls ()
1541 "Toggle TLS encryption mode for gopher."
1543 (setq elpher-use-tls (not elpher-use-tls))
1545 (if (gnutls-available-p)
1546 (message "TLS gopher mode enabled. (Will not affect current page until reload.)")
1547 (setq elpher-use-tls nil)
1548 (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1549 (message "TLS gopher mode disabled. (Will not affect current page until reload.)")))
1551 (defun elpher-view-raw ()
1552 "View raw server response for current page."
1554 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1555 (error "This page was not generated by a server")
1556 (elpher-visit-page elpher-current-page
1557 #'elpher-render-raw)))
1559 (defun elpher-back ()
1560 "Go to previous site."
1562 (elpher-visit-previous-page))
1564 (defun elpher-back-to-start ()
1565 "Go all the way back to the start page."
1567 (setq elpher-current-page nil)
1568 (setq elpher-history nil)
1569 (let ((start-page (elpher-make-page "Elpher Start Page"
1570 (elpher-make-special-address 'start))))
1571 (elpher-visit-page start-page)))
1573 (defun elpher-download ()
1574 "Download the link at point."
1576 (let ((button (button-at (point))))
1578 (let ((page (button-get button 'elpher-page)))
1579 (if (elpher-address-special-p (elpher-page-address page))
1580 (error "Cannot download %s"
1581 (elpher-page-display-string page))
1582 (elpher-visit-page (button-get button 'elpher-page)
1583 #'elpher-render-download)))
1584 (error "No link selected"))))
1586 (defun elpher-download-current ()
1587 "Download the current page."
1589 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1590 (error "Cannot download %s"
1591 (elpher-page-display-string elpher-current-page))
1592 (elpher-visit-page (elpher-make-page
1593 (elpher-page-display-string elpher-current-page)
1594 (elpher-page-address elpher-current-page))
1595 #'elpher-render-download
1598 (defun elpher-build-link-map ()
1599 "Build alist mapping link names to destination pages in current buffer."
1600 (let ((link-map nil)
1601 (b (next-button (point-min) t)))
1603 (push (cons (button-label b) b) link-map)
1604 (setq b (next-button (button-start b))))
1607 (defun elpher-jump ()
1608 "Select a directory entry by name. Similar to the info browser (m)enu command."
1610 (let* ((link-map (elpher-build-link-map)))
1612 (let ((key (let ((completion-ignore-case t))
1613 (completing-read "Directory item/link: "
1615 (if (and key (> (length key) 0))
1616 (let ((b (cdr (assoc key link-map))))
1617 (goto-char (button-start b))
1618 (button-activate b)))))))
1620 (defun elpher-root-dir ()
1621 "Visit root of current server."
1623 (let ((address (elpher-page-address elpher-current-page)))
1624 (if (not (elpher-address-special-p address))
1625 (if (or (member (url-filename address) '("/" ""))
1626 (and (elpher-address-gopher-p address)
1627 (= (length (elpher-gopher-address-selector address)) 0)))
1628 (error "Already at root directory of current server")
1629 (let ((address-copy (elpher-address-from-url
1630 (elpher-address-to-url address))))
1631 (setf (url-filename address-copy) "")
1632 (elpher-go (elpher-address-to-url address-copy))))
1633 (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1635 (defun elpher-bookmarks-current-p ()
1636 "Return non-nil if current page is a bookmarks page."
1637 (equal (elpher-address-type (elpher-page-address elpher-current-page))
1638 '(special bookmarks)))
1640 (defun elpher-reload-bookmarks ()
1641 "Reload bookmarks if current page is a bookmarks page."
1642 (if (elpher-bookmarks-current-p)
1643 (elpher-reload-current-page)))
1645 (defun elpher-bookmark-current ()
1646 "Bookmark the current page."
1648 (let ((address (elpher-page-address elpher-current-page))
1649 (display-string (elpher-page-display-string elpher-current-page)))
1650 (if (not (elpher-address-special-p address))
1651 (let ((bookmark-display-string (read-string "Bookmark display string: "
1653 (elpher-add-address-bookmark address bookmark-display-string)
1654 (message "Bookmark added."))
1655 (error "Cannot bookmark %s" display-string))))
1657 (defun elpher-bookmark-link ()
1658 "Bookmark the link at point."
1660 (let ((button (button-at (point))))
1662 (let* ((page (button-get button 'elpher-page))
1663 (address (elpher-page-address page))
1664 (display-string (elpher-page-display-string page)))
1665 (if (not (elpher-address-special-p address))
1666 (let ((bookmark-display-string (read-string "Bookmark display string: "
1668 (elpher-add-address-bookmark address bookmark-display-string)
1669 (elpher-reload-bookmarks)
1670 (message "Bookmark added."))
1671 (error "Cannot bookmark %s" display-string)))
1672 (error "No link selected"))))
1674 (defun elpher-unbookmark-current ()
1675 "Remove bookmark for the current page."
1677 (let ((address (elpher-page-address elpher-current-page)))
1678 (unless (elpher-address-special-p address)
1679 (elpher-remove-address-bookmark address)
1680 (message "Bookmark removed."))))
1682 (defun elpher-unbookmark-link ()
1683 "Remove bookmark for the link at point."
1685 (let ((button (button-at (point))))
1687 (let ((page (button-get button 'elpher-page)))
1688 (elpher-remove-address-bookmark (elpher-page-address page))
1689 (elpher-reload-bookmarks)
1690 (message "Bookmark removed."))
1691 (error "No link selected"))))
1693 (defun elpher-bookmarks ()
1694 "Visit bookmarks page."
1696 (switch-to-buffer "*elpher*")
1698 (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1700 (defun elpher-info-page (page)
1701 "Display information on PAGE."
1702 (let ((display-string (elpher-page-display-string page))
1703 (address (elpher-page-address page)))
1704 (if (elpher-address-special-p address)
1705 (message "Special page: %s" display-string)
1706 (message "%s" (elpher-address-to-url address)))))
1708 (defun elpher-info-link ()
1709 "Display information on page corresponding to link at point."
1711 (let ((button (button-at (point))))
1713 (elpher-info-page (button-get button 'elpher-page))
1714 (error "No item selected"))))
1716 (defun elpher-info-current ()
1717 "Display information on current page."
1719 (elpher-info-page elpher-current-page))
1721 (defun elpher-copy-page-url (page)
1722 "Copy URL representation of address of PAGE to `kill-ring'."
1723 (let ((address (elpher-page-address page)))
1724 (if (elpher-address-special-p address)
1725 (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1726 (let ((url (elpher-address-to-url address)))
1727 (message "Copied \"%s\" to kill-ring/clipboard." url)
1730 (defun elpher-copy-link-url ()
1731 "Copy URL of item at point to `kill-ring'."
1733 (let ((button (button-at (point))))
1735 (elpher-copy-page-url (button-get button 'elpher-page))
1736 (error "No item selected"))))
1738 (defun elpher-copy-current-url ()
1739 "Copy URL of current page to `kill-ring'."
1741 (elpher-copy-page-url elpher-current-page))
1743 (defun elpher-set-gopher-coding-system ()
1744 "Specify an explicit character coding system for gopher selectors."
1746 (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1747 (setq elpher-user-coding-system system)
1749 (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1750 (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1756 (defvar elpher-mode-map
1757 (let ((map (make-sparse-keymap)))
1758 (define-key map (kbd "TAB") 'elpher-next-link)
1759 (define-key map (kbd "<backtab>") 'elpher-prev-link)
1760 (define-key map (kbd "C-M-i") 'elpher-prev-link)
1761 (define-key map (kbd "u") 'elpher-back)
1762 (define-key map (kbd "U") 'elpher-back-to-start)
1763 (define-key map [mouse-3] 'elpher-back)
1764 (define-key map (kbd "O") 'elpher-root-dir)
1765 (define-key map (kbd "g") 'elpher-go)
1766 (define-key map (kbd "o") 'elpher-go-current)
1767 (define-key map (kbd "r") 'elpher-redraw)
1768 (define-key map (kbd "R") 'elpher-reload)
1769 (define-key map (kbd "T") 'elpher-toggle-tls)
1770 (define-key map (kbd ".") 'elpher-view-raw)
1771 (define-key map (kbd "d") 'elpher-download)
1772 (define-key map (kbd "D") 'elpher-download-current)
1773 (define-key map (kbd "m") 'elpher-jump)
1774 (define-key map (kbd "i") 'elpher-info-link)
1775 (define-key map (kbd "I") 'elpher-info-current)
1776 (define-key map (kbd "c") 'elpher-copy-link-url)
1777 (define-key map (kbd "C") 'elpher-copy-current-url)
1778 (define-key map (kbd "a") 'elpher-bookmark-link)
1779 (define-key map (kbd "A") 'elpher-bookmark-current)
1780 (define-key map (kbd "x") 'elpher-unbookmark-link)
1781 (define-key map (kbd "X") 'elpher-unbookmark-current)
1782 (define-key map (kbd "B") 'elpher-bookmarks)
1783 (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1784 (when (fboundp 'evil-define-key*)
1785 (evil-define-key* 'motion map
1786 (kbd "TAB") 'elpher-next-link
1787 (kbd "C-") 'elpher-follow-current-link
1788 (kbd "C-t") 'elpher-back
1789 (kbd "u") 'elpher-back
1790 (kbd "U") 'elpher-back-to-start
1791 [mouse-3] 'elpher-back
1792 (kbd "g") 'elpher-go
1793 (kbd "o") 'elpher-go-current
1794 (kbd "r") 'elpher-redraw
1795 (kbd "R") 'elpher-reload
1796 (kbd "T") 'elpher-toggle-tls
1797 (kbd ".") 'elpher-view-raw
1798 (kbd "d") 'elpher-download
1799 (kbd "D") 'elpher-download-current
1800 (kbd "m") 'elpher-jump
1801 (kbd "i") 'elpher-info-link
1802 (kbd "I") 'elpher-info-current
1803 (kbd "c") 'elpher-copy-link-url
1804 (kbd "C") 'elpher-copy-current-url
1805 (kbd "a") 'elpher-bookmark-link
1806 (kbd "A") 'elpher-bookmark-current
1807 (kbd "x") 'elpher-unbookmark-link
1808 (kbd "X") 'elpher-unbookmark-current
1809 (kbd "B") 'elpher-bookmarks
1810 (kbd "S") 'elpher-set-gopher-coding-system))
1812 "Keymap for gopher client.")
1814 (define-derived-mode elpher-mode special-mode "elpher"
1815 "Major mode for elpher, an elisp gopher client.
1817 This mode is automatically enabled by the interactive
1818 functions which initialize the gopher client, namely
1819 `elpher', `elpher-go' and `elpher-bookmarks'.")
1821 (when (fboundp 'evil-set-initial-state)
1822 (evil-set-initial-state 'elpher-mode 'motion))
1825 ;;; Main start procedure
1830 "Start elpher with default landing page."
1832 (if (get-buffer "*elpher*")
1833 (switch-to-buffer "*elpher*")
1834 (switch-to-buffer "*elpher*")
1835 (setq elpher-current-page nil)
1836 (setq elpher-history nil)
1837 (let ((start-page (elpher-make-page "Elpher Start Page"
1838 (elpher-make-special-address 'start))))
1839 (elpher-visit-page start-page)))
1840 "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1842 ;;; elpher.el ends here