Improved error handling, command hints.
[elpher.git] / elpher.el
1 ;;; elpher.el --- a friendly gopher client.
2
3 ;; Copyright (C) 2019 Tim Vaughan
4
5 ;; Author: Tim Vaughan <tgvaughan@gmail.com>
6 ;; Created: 11 April 2019
7 ;; Version: 1.2.0
8 ;; Keywords: comm gopher
9 ;; Homepage: https://github.com/tgvaughan/elpher
10 ;; Package-Requires: ((emacs "25"))
11
12 ;; This file is not part of GNU Emacs.
13
14 ;; This program is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Elpher aims to provide a practical gopher client for GNU Emacs.
30 ;; It supports:
31
32 ;; - intuitive keyboard and mouse-driven interface,
33 ;; - caching of visited sites (both content and cursor position),
34 ;; - pleasant and configurable colouring of Gopher directories,
35 ;; - direct visualisation of image files,
36 ;; - (m)enu key support, similar to Emacs' info browser,
37 ;; - clickable web and gopher links in plain text,
38 ;; - a simple bookmark management system.
39
40 ;; Visited pages are stored as a hierarchy rather than a linear history,
41 ;; meaning that navigation between these pages is quick and easy.
42
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.
46
47 ;; Faces, caching options and start page can be configured via
48 ;; the Elpher customization group in Applications.
49
50 ;;; Code:
51
52 (provide 'elpher)
53 (require 'seq)
54 (require 'pp)
55
56 ;;; Global constants
57 ;;
58
59 (defconst elpher-version "1.2.0"
60   "Current version of elpher.")
61
62 (defconst elpher-margin-width 6
63   "Width of left-hand margin used when rendering indicies.")
64
65 (defconst elpher-start-index
66   (mapconcat
67    'identity
68    (list "i\tfake\tfake\t1"
69          "i     --------------------------------------------\tfake\tfake\t1"
70          "i                Elpher Gopher Client             \tfake\tfake\t1"
71          (format "i                   version %s\tfake\tfake\t1" elpher-version)
72          "i     --------------------------------------------\tfake\tfake\t1"
73          "i\tfake\tfake\t1"
74          "iUsage:\tfake\tfake\t1"
75          "i\tfake\tfake\t1"
76          "i - tab/shift-tab: next/prev item on current page\tfake\tfake\t1"
77          "i - RET/mouse-1: open item under cursor\tfake\tfake\t1"
78          "i - m: select an item on current page by name (autocompletes)\tfake\tfake\t1"
79          "i - u: return to parent\tfake\tfake\t1"
80          "i - O: visit the root menu of the current server\tfake\tfake\t1"
81          "i - g: go to a particular menu or item\tfake\tfake\t1"
82          "i - i/I: info on item under cursor or current page\tfake\tfake\t1"
83          "i - c/C: copy URL representation of item under cursor or current page\tfake\tfake\t1"
84          "i - a/A: bookmark the item under cursor or current page\tfake\tfake\t1"
85          "i - x/X: remove bookmark for item under cursor or current page\tfake\tfake\t1"
86          "i - B: visit the bookmarks page\tfake\tfake\t1"
87          "i - r: redraw current page (using cached contents if available)\tfake\tfake\t1"
88          "i - R: reload current page (regenerates cache)\tfake\tfake\t1"
89          "i - d: download directory entry under cursor\tfake\tfake\t1"
90          "i - w: display the raw server response for the current page\tfake\tfake\t1"
91          "i\tfake\tfake\t1"
92          "iWhere to start exploring Gopherspace:\tfake\tfake\t1"
93          "i\tfake\tfake\t1"
94          "1Floodgap Systems Gopher Server\t/\tgopher.floodgap.com\t70"
95          "i\tfake\tfake\t1"
96          "iAlternatively, select the following item and enter some\tfake\tfake\t1"
97          "isearch terms:\tfake\tfake\t1"
98          "i\tfake\tfake\t1"
99          "7Veronica-2 Gopher Search Engine\t/v2/vs\tgopher.floodgap.com\t70"
100          ".\r\n")
101    "\r\n")
102   "Source for elpher start page.")
103
104 (defconst elpher-type-map
105   '((?0 elpher-get-text-node "T" elpher-text)
106     (?1 elpher-get-index-node "/" elpher-index)
107     (?4 elpher-get-node-download "B" elpher-binary)
108     (?5 elpher-get-node-download "B" elpher-binary)
109     (?7 elpher-get-search-node "?" elpher-search)
110     (?8 elpher-get-telnet-node "?" elpher-telnet)
111     (?9 elpher-get-node-download "B" elpher-binary)
112     (?g elpher-get-image-node "im" elpher-image)
113     (?p elpher-get-image-node "im" elpher-image)
114     (?I elpher-get-image-node "im" elpher-image)
115     (?h elpher-get-url-node "W" elpher-url)
116     (bookmarks elpher-get-bookmarks-node "#" elpher-index)
117     (start elpher-get-start-node "#" elpher-index))
118   "Association list from types to getters, margin codes and index faces.")
119
120
121 ;;; Customization group
122 ;;
123
124 (defgroup elpher nil
125   "A gopher client."
126   :group 'applications)
127
128 ;; Face customizations
129
130 (defface elpher-index
131   '((t :inherit font-lock-keyword-face))
132   "Face used for directory type directory records.")
133
134 (defface elpher-text
135   '((t :inherit bold))
136   "Face used for text type directory records.")
137
138 (defface elpher-info
139   '((t :inherit default))
140   "Face used for info type directory records.")
141
142 (defface elpher-image
143   '((t :inherit font-lock-string-face))
144   "Face used for image type directory records.")
145
146 (defface elpher-search
147   '((t :inherit warning))
148   "Face used for search type directory records.")
149
150 (defface elpher-url
151   '((t :inherit font-lock-comment-face))
152   "Face used for url type directory records.")
153
154 (defface elpher-telnet
155   '((t :inherit font-lock-function-name-face))
156   "Face used for telnet type directory records.")
157
158 (defface elpher-binary
159   '((t :inherit font-lock-doc-face))
160   "Face used for binary type directory records.")
161
162 (defface elpher-unknown
163   '((t :inherit error))
164   "Face used for directory records with unknown/unsupported types.")
165
166 (defface elpher-margin-key
167   '((t :inherit bold))
168   "Face used for directory margin key.")
169
170 (defface elpher-margin-brackets
171   '((t :inherit shadow))
172   "Face used for brackets around directory margin key.")
173
174 ;; Other customizations
175
176 (defcustom elpher-open-urls-with-eww nil
177   "If non-nil, open URL selectors using eww.
178 Otherwise, use the system browser via the BROWSE-URL function."
179   :type '(boolean))
180
181 (defcustom elpher-buttonify-urls-in-directories nil
182   "If non-nil, turns URLs matched in directories into clickable buttons."
183   :type '(boolean))
184
185 (defcustom elpher-cache-images nil
186   "If non-nil, cache images in memory in the same way as other content."
187   :type '(boolean))
188
189 (defcustom elpher-use-header t
190   "If non-nil, display current node information in buffer header."
191   :type '(boolean))
192
193 ;;; Model
194 ;;
195
196 ;; Address
197
198 (defun elpher-make-address (type &optional selector host port)
199   "Create an address of a gopher object with TYPE, SELECTOR, HOST and PORT.
200 Although selector host and port are optional, they are only omitted for
201 special address types, such as 'start for the start page."
202   (list type selector host port))
203
204 (defun elpher-address-type (address)
205   "Retrieve type from ADDRESS."
206   (elt address 0))
207
208 (defun elpher-address-selector (address)
209   "Retrieve selector from ADDRESS."
210   (elt address 1))
211
212 (defun elpher-address-host (address)
213   "Retrieve host from ADDRESS."
214   (elt address 2))
215
216 (defun elpher-address-port (address)
217   "Retrieve port from ADDRESS."
218   (elt address 3))
219
220 (defun elpher-address-special-p (address)
221   (not (elpher-address-host address)))
222
223 ;; Node
224
225 (defun elpher-make-node (display-string parent address)
226   "Create a node in the gopher page hierarchy.
227
228 DISPLAY-STRING records the display string used for the page.
229
230 PARENT specifies the parent of the node, and ADDRESS specifies the
231 address of the gopher page."
232   (list display-string parent address))
233
234 (defun elpher-node-display-string (node)
235   "Retrieve the display string of NODE."
236   (elt node 0))
237
238 (defun elpher-node-parent (node)
239   "Retrieve the parent node of NODE."
240   (elt node 1))
241
242 (defun elpher-node-address (node)
243   "Retrieve the address of NODE."
244   (elt node 2))
245
246 ;; Cache
247
248 (defvar elpher-content-cache (make-hash-table :test 'equal))
249 (defvar elpher-pos-cache (make-hash-table :test 'equal))
250
251 (defun elpher-get-cached-content (address)
252   "Retrieve the cached content for ADDRESS, or nil if none exists."
253   (gethash address elpher-content-cache))
254
255 (defun elpher-cache-content (address content)
256   "Set the content cache for ADDRESS to CONTENT."
257   (puthash address content elpher-content-cache))
258
259 (defun elpher-get-cached-pos (address)
260   "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
261   (gethash address elpher-pos-cache))
262
263 (defun elpher-cache-pos (address pos)
264   "Set the cursor position cache for ADDRESS to POS."
265   (puthash address pos elpher-pos-cache))
266
267 ;; Node graph traversal
268
269 (defvar elpher-current-node nil)
270
271 (defun elpher-visit-node (node &optional getter)
272   "Visit NODE using its own getter or GETTER, if non-nil."
273   (elpher-save-pos)
274   (elpher-process-cleanup)
275   (setq elpher-current-node node)
276   (if getter
277       (funcall getter)
278     (let* ((address (elpher-node-address node))
279            (type (elpher-address-type address)))
280       (funcall (car (alist-get type elpher-type-map))))))
281
282 (defun elpher-visit-parent-node ()
283   "Visit the parent of the current node."
284   (let ((parent-node (elpher-node-parent elpher-current-node)))
285     (when parent-node
286       (elpher-visit-node parent-node))))
287       
288 (defun elpher-reload-current-node ()
289   "Reload the current node, discarding any existing cached content."
290   (elpher-cache-content (elpher-node-address elpher-current-node) nil)
291   (elpher-visit-node elpher-current-node))
292
293 (defun elpher-save-pos ()
294   "Save the current position of point to the current node."
295   (when elpher-current-node
296     (elpher-cache-pos (elpher-node-address elpher-current-node) (point))))
297
298 (defun elpher-restore-pos ()
299   "Restore the position of point to that cached in the current node."
300   (let ((pos (elpher-get-cached-pos (elpher-node-address elpher-current-node))))
301     (if pos
302         (goto-char pos)
303       (goto-char (point-min)))))
304
305
306 ;;; Buffer preparation
307 ;;
308
309 (defun elpher-update-header ()
310   "If `elpher-use-header' is true, display current node info in window header."
311   (if elpher-use-header
312       (setq header-line-format (elpher-node-display-string elpher-current-node))))
313
314 (defmacro elpher-with-clean-buffer (&rest args)
315   "Evaluate ARGS with a clean *elpher* buffer as current."
316   (list 'with-current-buffer "*elpher*"
317         '(elpher-mode)
318         (append (list 'let '((inhibit-read-only t))
319                       '(erase-buffer)
320                       '(elpher-update-header))
321                 args)))
322
323
324 ;;; Index rendering
325 ;;
326
327 (defun elpher-preprocess-text-response (string)
328   "Clear away CRs and terminating period from STRING."
329   (replace-regexp-in-string "\n\.\n$" "\n"
330                             (replace-regexp-in-string "\r" ""
331                                                       string)))
332
333 (defun elpher-insert-index (string)
334   "Insert the index corresponding to STRING into the current buffer."
335   ;; Should be able to split directly on CRLF, but some non-conformant
336   ;; LF-only servers sadly exist, hence the following.
337   (let ((str-processed (elpher-preprocess-text-response string)))
338     (dolist (line (split-string str-processed "\n"))
339       (unless (= (length line) 0)
340         (let* ((type (elt line 0))
341                (fields (split-string (substring line 1) "\t"))
342                (display-string (elt fields 0))
343                (selector (elt fields 1))
344                (host (elt fields 2))
345                (port (if (elt fields 3)
346                          (string-to-number (elt fields 3))
347                        nil)))
348           (elpher-insert-index-record display-string type selector host port))))))
349
350 (defun elpher-insert-margin (&optional type-name)
351   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
352   (if type-name
353       (progn
354         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
355                         (concat
356                          (propertize "[" 'face 'elpher-margin-brackets)
357                          (propertize type-name 'face 'elpher-margin-key)
358                          (propertize "]" 'face 'elpher-margin-brackets))))
359         (insert " "))
360     (insert (make-string elpher-margin-width ?\s))))
361
362 (defun elpher-node-button-help (node)
363   "Return a string containing the help text for a button corresponding to NODE."
364   (let ((address (elpher-node-address node)))
365     (if (eq (elpher-address-type address) ?h)
366         (let ((url (cadr (split-string (elpher-address-selector address) "URL:"))))
367           (format "mouse-1, RET: open url '%s'" url))
368       (format "mouse-1, RET: open '%s' on %s port %s"
369               (elpher-address-selector address)
370               (elpher-address-host address)
371               (elpher-address-port address)))))
372
373 (defun elpher-insert-index-record (display-string type selector host port)
374   "Function to insert an index record into the current buffer.
375 The contents of the record are dictated by TYPE, DISPLAY-STRING, SELECTOR, HOST
376 and PORT."
377   (let ((address (elpher-make-address type selector host port))
378         (type-map-entry (alist-get type elpher-type-map)))
379     (if type-map-entry
380         (let* ((margin-code (elt type-map-entry 1))
381                (face (elt type-map-entry 2))
382                (node (elpher-make-node display-string elpher-current-node address)))
383           (elpher-insert-margin margin-code)
384           (insert-text-button display-string
385                               'face face
386                               'elpher-node node
387                               'action #'elpher-click-link
388                               'follow-link t
389                               'help-echo (elpher-node-button-help node)))
390       (pcase type
391         (?i ;; Information
392          (elpher-insert-margin)
393          (insert (propertize
394                   (if elpher-buttonify-urls-in-directories
395                       (elpher-buttonify-urls display-string)
396                     display-string)
397                   'face 'elpher-info)))
398         (other ;; Unknown
399          (elpher-insert-margin (concat (char-to-string type) "?"))
400          (insert (propertize display-string
401                              'face 'elpher-unknown)))))
402     (insert "\n")))
403
404 (defun elpher-click-link (button)
405   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
406   (let ((node (button-get button 'elpher-node)))
407     (elpher-visit-node node)))
408
409
410 ;;; Selector retrieval (all kinds)
411 ;;
412
413 (defun elpher-process-cleanup ()
414   "Immediately shut down any extant elpher process."
415   (let ((p (get-process "elpher-process")))
416     (if p (delete-process p))))
417
418 (defvar elpher-selector-string)
419
420 (defun elpher-get-selector (address after)
421   "Retrieve selector specified by ADDRESS, then execute AFTER.
422 The result is stored as a string in the variable â€˜elpher-selector-string’."
423   (setq elpher-selector-string "")
424   (condition-case nil
425       (progn
426         (make-network-process :name "elpher-process"
427                               :host (elpher-address-host address)
428                               :service (elpher-address-port address)
429                               :filter (lambda (proc string)
430                                         (setq elpher-selector-string
431                                               (concat elpher-selector-string string)))
432                               :sentinel after)
433         (process-send-string "elpher-process"
434                              (concat (elpher-address-selector address) "\n")))
435     (error
436      (elpher-with-clean-buffer
437       (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
438               "Failed to connect to " (elpher-get-address-url address) ".\n"
439               (propertize "\n----------------\n\n" 'face 'error)
440               "Press 'u' to return to the previous page.")))))
441
442 ;; Index retrieval
443
444 (defun elpher-get-index-node ()
445   "Getter which retrieves the current node contents as an index."
446   (let* ((address (elpher-node-address elpher-current-node))
447          (content (elpher-get-cached-content address)))
448     (if content
449         (progn
450           (elpher-with-clean-buffer
451            (insert content)
452            (elpher-restore-pos)))
453       (elpher-with-clean-buffer
454        (insert "LOADING DIRECTORY... (use 'u' to cancel)"))
455       (elpher-get-selector address
456                            (lambda (proc event)
457                              (unless (string-prefix-p "deleted" event)
458                                (elpher-with-clean-buffer
459                                 (elpher-insert-index elpher-selector-string)
460                                 (elpher-restore-pos)
461                                 (elpher-cache-content
462                                  (elpher-node-address elpher-current-node)
463                                  (buffer-string)))))))))
464
465 ;; Text retrieval
466
467 (defconst elpher-url-regex
468   "\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.\-]+\\)\\(?3::[0-9]+\\)?\\(?4:/[^ \r\n\t(),]*\\)?"
469   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
470
471 (defun elpher-make-node-from-matched-url (parent &optional string)
472   "Convert most recent `elpher-url-regex' match to a node.
473
474 PARENT defines the node to set as the parent to the new node.
475
476 If STRING is non-nil, this is given as an argument to all `match-string'
477 calls, as is necessary if the match is performed by `string-match'."
478   (let ((url (match-string 0 string))
479         (protocol (downcase (match-string 1 string))))
480     (if (string= protocol "gopher")
481         (let* ((host (match-string 2 string))
482                (port (if (> (length (match-string 3 string))  1)
483                          (string-to-number (substring (match-string 3 string) 1))
484                        70))
485                (type-and-selector (match-string 4 string))
486                (type (if (> (length type-and-selector) 1)
487                          (elt type-and-selector 1)
488                        ?1))
489                (selector (if (> (length type-and-selector) 1)
490                              (substring type-and-selector 2)
491                            ""))
492                (address (elpher-make-address type selector host port)))
493           (elpher-make-node url elpher-current-node address))
494       (let* ((host (match-string 2 string))
495              (port (if (> (length (match-string 3 string)) 1)
496                        (string-to-number (substring (match-string 3 string) 1))
497                      70))
498              (selector (concat "URL:" url))
499              (address (elpher-make-address ?h selector host port)))
500         (elpher-make-node url elpher-current-node address)))))
501
502
503 (defun elpher-buttonify-urls (string)
504   "Turn substrings which look like urls in STRING into clickable buttons."
505   (with-temp-buffer
506     (insert string)
507     (goto-char (point-min))
508     (while (re-search-forward elpher-url-regex nil t)
509         (let ((node (elpher-make-node-from-matched-url elpher-current-node)))
510           (make-text-button (match-beginning 0)
511                             (match-end 0)
512                             'elpher-node  node
513                             'action #'elpher-click-link
514                             'follow-link t
515                             'help-echo (elpher-node-button-help node))))
516     (buffer-string)))
517
518 (defun elpher-get-text-node ()
519   "Getter which retrieves the current node contents as a text document."
520   (let* ((address (elpher-node-address elpher-current-node))
521          (content (elpher-get-cached-content address)))
522     (if content
523         (progn
524           (elpher-with-clean-buffer
525            (insert content)
526            (elpher-restore-pos)))
527       (progn
528         (elpher-with-clean-buffer
529          (insert "LOADING TEXT... (use 'u' to cancel)"))
530         (elpher-get-selector address
531                               (lambda (proc event)
532                                 (unless (string-prefix-p "deleted" event)
533                                   (elpher-with-clean-buffer
534                                    (insert (elpher-buttonify-urls
535                                             (elpher-preprocess-text-response
536                                              elpher-selector-string)))
537                                    (elpher-restore-pos)
538                                    (elpher-cache-content
539                                     (elpher-node-address elpher-current-node)
540                                     (buffer-string))))))))))
541
542 ;; Image retrieval
543
544 (defun elpher-get-image-node ()
545   "Getter which retrieves the current node contents as an image to view."
546   (let* ((address (elpher-node-address elpher-current-node))
547          (content (elpher-get-cached-content address)))
548     (if content
549         (progn
550           (elpher-with-clean-buffer
551            (insert-image content)
552            (elpher-restore-pos)))
553       (if (display-images-p)
554           (progn
555             (elpher-with-clean-buffer
556              (insert "LOADING IMAGE... (use 'u' to cancel)"))
557             (elpher-get-selector address
558                                  (lambda (proc event)
559                                    (unless (string-prefix-p "deleted" event)
560                                      (let ((image (create-image
561                                                    (encode-coding-string
562                                                     elpher-selector-string
563                                                     'no-conversion)
564                                                    nil t)))
565                                        (elpher-with-clean-buffer
566                                         (insert-image image)
567                                         (elpher-restore-pos))
568                                        (if elpher-cache-images
569                                            (elpher-cache-content
570                                             (elpher-node-address elpher-current-node)
571                                             image)))))))
572         (elpher-get-node-download)))))
573
574 ;; Search retrieval
575
576 (defun elpher-get-search-node ()
577   "Getter which submits a search query to the address of the current node."
578   (let* ((address (elpher-node-address elpher-current-node))
579          (content (elpher-get-cached-content address))
580          (aborted t))
581     (if content
582         (progn
583           (elpher-with-clean-buffer
584            (insert content)
585            (elpher-restore-pos))
586           (message "Displaying cached search results.  Reload to perform a new search."))
587       (unwind-protect
588           (let* ((query-string (read-string "Query: "))
589                  (query-selector (concat (elpher-address-selector address) "\t" query-string))
590                  (search-address (elpher-make-address ?1
591                                                       query-selector
592                                                       (elpher-address-host address)
593                                                       (elpher-address-port address))))
594             (setq aborted nil)
595             (elpher-with-clean-buffer
596              (insert "LOADING RESULTS... (use 'u' to cancel)"))
597             (elpher-get-selector search-address
598                                   (lambda (proc event)
599                                     (unless (string-prefix-p "deleted" event)
600                                       (elpher-with-clean-buffer
601                                        (elpher-insert-index elpher-selector-string))
602                                       (goto-char (point-min))
603                                       (elpher-cache-content
604                                        (elpher-node-address elpher-current-node)
605                                        (buffer-string))))))
606         (if aborted
607             (elpher-visit-parent-node))))))
608
609 ;; Raw server response retrieval
610
611 (defun elpher-get-node-raw ()
612   "Getter which retrieves the raw server response for the current node."
613   (let ((address (elpher-node-address elpher-current-node)))
614     (elpher-with-clean-buffer
615      (insert "LOADING RAW SERVER RESPONSE... (use 'u' to cancel)"))
616     (if address
617         (elpher-get-selector address
618                               (lambda (proc event)
619                                 (unless (string-prefix-p "deleted" event)
620                                   (elpher-with-clean-buffer
621                                    (insert elpher-selector-string)
622                                    (goto-char (point-min))))))
623       (progn
624         (elpher-with-clean-buffer
625          (insert elpher-start-index))
626         (goto-char (point-min)))))
627   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
628  
629 ;; File export retrieval
630
631 (defvar elpher-download-filename)
632
633 (defun elpher-get-node-download ()
634   "Getter which retrieves the current node and writes the result to a file."
635   (let* ((address (elpher-node-address elpher-current-node))
636          (selector (elpher-address-selector address)))
637     (elpher-visit-parent-node) ; Do first in case of non-local exits.
638     (let* ((filename-proposal (file-name-nondirectory selector))
639            (filename (read-file-name "Save file as: "
640                                      nil nil nil
641                                      (if (> (length filename-proposal) 0)
642                                          filename-proposal
643                                        "gopher.file"))))
644       (message "Downloading...")
645       (setq elpher-download-filename filename)
646       (elpher-get-selector address
647                             (lambda (proc event)
648                               (let ((coding-system-for-write 'binary))
649                                 (with-temp-file elpher-download-filename
650                                   (insert elpher-selector-string)
651                                   (message (format "Download complate, saved to file %s."
652                                                    elpher-download-filename)))))))))
653
654 ;; URL retrieval
655
656 (defun elpher-get-url-node ()
657   "Getter which attempts to open the URL specified by the current node."
658   (let* ((address (elpher-node-address elpher-current-node))
659          (selector (elpher-address-selector address)))
660     (elpher-visit-parent-node) ; Do first in case of non-local exits.
661     (let ((url (elt (split-string selector "URL:") 1)))
662       (if elpher-open-urls-with-eww
663           (browse-web url)
664         (browse-url url)))))
665
666 ;; Telnet node connection
667
668 (defun elpher-get-telnet-node ()
669   "Getter which opens a telnet connection to the server specified by the current node."
670   (let* ((address (elpher-node-address elpher-current-node))
671          (host (elpher-address-host address))
672          (port (elpher-address-port address)))
673     (elpher-visit-parent-node)
674     (telnet host port)))
675
676 ;; Start page node retrieval
677
678 (defun elpher-get-start-node ()
679   "Getter which displays the start page."
680   (elpher-with-clean-buffer
681    (elpher-insert-index elpher-start-index)
682    (elpher-restore-pos)))
683
684 ;; Bookmarks page node retrieval
685
686 (defun elpher-get-bookmarks-node ()
687   "Getter which loads and displays the current bookmark list."
688   (elpher-with-clean-buffer
689    (insert "---- Bookmark list ----\n\n")
690    (let ((bookmarks (elpher-load-bookmarks)))
691      (if bookmarks
692          (dolist (bookmark bookmarks)
693            (let ((display-string (elpher-bookmark-display-string bookmark))
694                  (address (elpher-bookmark-address bookmark)))
695              (elpher-insert-index-record display-string
696                                          (elpher-address-type address)
697                                          (elpher-address-selector address)
698                                          (elpher-address-host address)
699                                          (elpher-address-port address))))
700        (insert "No bookmarks found.\n")))
701    (insert "\n-----------------------\n\n"
702            "- u: return to previous page\n"
703            "- x: delete selected bookmark\n"
704            "- a: rename selected bookmark\n\n"
705            "Bookmarks are stored in the file "
706            (locate-user-emacs-file "elpher-bookmarks")) 
707    (elpher-restore-pos)))
708   
709
710 ;;; Bookmarks
711 ;;
712
713 (defun elpher-make-bookmark (display-string address)
714   "Make an elpher bookmark.
715 DISPLAY-STRING determines how the bookmark will appear in the
716 bookmark list, while ADDRESS is the address of the entry."
717   (list display-string address))
718   
719 (defun elpher-bookmark-display-string (bookmark)
720   "Get the display string of BOOKMARK."
721   (elt bookmark 0))
722
723 (defun elpher-set-bookmark-display-string (bookmark display-string)
724   "Set the display string of BOOKMARK to DISPLAY-STRING."
725   (setcar bookmark display-string))
726
727 (defun elpher-bookmark-address (bookmark)
728   "Get the address for BOOKMARK."
729   (elt bookmark 1))
730
731 (defun elpher-save-bookmarks (bookmarks)
732   "Record the bookmark list BOOKMARKS to the user's bookmark file.
733 Beware that this completely replaces the existing contents of the file."
734   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
735     (erase-buffer)
736     (insert "; Elpher gopher bookmarks file\n\n"
737             "; Bookmarks are stored as a list of (label (type selector host port))\n"
738             "; s-expressions, where type is stored as a character (i.e. 49 = ?1).\n"
739             "; Feel free to edit by hand, but ensure this structure remains intact.\n\n")
740     (pp bookmarks (current-buffer))))
741
742 (defun elpher-load-bookmarks ()
743   "Get the list of bookmarks from the users's bookmark file."
744   (with-temp-buffer
745     (ignore-errors
746       (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
747       (goto-char (point-min))
748       (read (current-buffer)))))
749
750 (defun elpher-add-address-bookmark (address display-string)
751   "Save a bookmark for ADDRESS with label DISPLAY-STRING.
752 If ADDRESS is already bookmarked, update the label only."
753   (let ((bookmarks (elpher-load-bookmarks)))
754     (let ((existing-bookmark (rassoc (list address) bookmarks)))
755       (if existing-bookmark
756           (elpher-set-bookmark-display-string existing-bookmark display-string)
757         (add-to-list 'bookmarks (elpher-make-bookmark display-string address))))
758     (elpher-save-bookmarks bookmarks)))
759
760 (defun elpher-remove-address-bookmark (address)
761   "Remove any bookmark to ADDRESS."
762     (elpher-save-bookmarks
763      (seq-filter (lambda (bookmark)
764                    (not (equal (elpher-bookmark-address bookmark) address)))
765                  (elpher-load-bookmarks))))
766
767 ;;; Interactive procedures
768 ;;
769
770 (defun elpher-next-link ()
771   "Move point to the next link on the current page."
772   (interactive)
773   (forward-button 1))
774
775 (defun elpher-prev-link ()
776   "Move point to the previous link on the current page."
777   (interactive)
778   (backward-button 1))
779
780 (defun elpher-follow-current-link ()
781   "Open the link or url at point."
782   (interactive)
783   (push-button))
784
785 (defun elpher-go ()
786   "Go to a particular gopher site read from the minibuffer.
787 The site may be specified via a URL or explicitly in terms of
788 host, selector and port."
789   (interactive)
790   (let ((node
791          (let ((host-or-url (read-string "Gopher host or URL: ")))
792            (if (string-match elpher-url-regex host-or-url)
793                (elpher-make-node-from-matched-url elpher-current-node
794                                                   host-or-url)
795              (let ((selector (read-string "Selector (default none): " nil nil ""))
796                    (port-string (read-string "Port (default 70): " nil nil "70")))
797                (elpher-make-node (concat "gopher://" host-or-url
798                                          ":" port-string
799                                          "/1" selector)
800                                  elpher-current-node
801                                  (elpher-make-address ?1 selector host-or-url
802                                                       (string-to-number port-string))))))))
803     (switch-to-buffer "*elpher*")
804     (elpher-visit-node node)))
805
806 (defun  elpher-redraw ()
807   "Redraw current page."
808   (interactive)
809   (if elpher-current-node
810       (elpher-visit-node elpher-current-node)
811     (message "No current site.")))
812
813 (defun  elpher-reload ()
814   "Reload current page."
815   (interactive)
816   (if elpher-current-node
817       (elpher-reload-current-node)
818     (message "No current site.")))
819
820 (defun elpher-view-raw ()
821   "View raw server response for current page."
822   (interactive)
823   (if elpher-current-node
824       (if (elpher-address-special-p (elpher-node-address elpher-current-node))
825           (error "This page was not generated by a server.")
826         (elpher-visit-node elpher-current-node
827                            #'elpher-get-node-raw))
828     (message "No current site.")))
829
830 (defun elpher-back ()
831   "Go to previous site."
832   (interactive)
833   (if (elpher-node-parent elpher-current-node)
834       (elpher-visit-parent-node)
835     (error "No previous site")))
836
837 (defun elpher-download ()
838   "Download the link at point."
839   (interactive)
840   (let ((button (button-at (point))))
841     (if button
842         (let ((node (button-get button 'elpher-node)))
843           (if (elpher-address-special-p (elpher-node-address node))
844               (error "Cannot download this link")
845             (elpher-visit-node (button-get button 'elpher-node)
846                                #'elpher-get-node-download)))
847       (error "No link selected"))))
848
849 (defun elpher-build-link-map ()
850   "Build alist mapping link names to destination nodes in current buffer."
851   (let ((link-map nil)
852         (b (next-button (point-min) t)))
853     (while b
854       (add-to-list 'link-map (cons (button-label b) b))
855       (setq b (next-button (button-start b))))
856     link-map))
857
858 (defun elpher-jump ()
859   "Select a directory entry by name.  Similar to the info browser (m)enu command."
860   (interactive)
861   (let* ((link-map (elpher-build-link-map)))
862     (if link-map
863         (let ((key (let ((completion-ignore-case t))
864                      (completing-read "Directory item/link: "
865                                       link-map nil t))))
866           (if (and key (> (length key) 0))
867               (let ((b (cdr (assoc key link-map))))
868                 (goto-char (button-start b))
869                 (button-activate b)))))))
870
871 (defun elpher-root-dir ()
872   "Visit root of current server."
873   (interactive)
874   (let* ((address (elpher-node-address elpher-current-node))
875          (host (elpher-address-host address)))
876     (if host
877         (let ((host (elpher-address-host address))
878               (selector (elpher-address-selector address))
879               (port (elpher-address-port address)))
880           (if (> (length selector) 0)
881               (let ((root-address (elpher-make-address ?1 "" host port)))
882                 (elpher-visit-node
883                  (elpher-make-node (concat "gopher://" host
884                                            ":" (number-to-string port)
885                                            "/1/")
886                                    elpher-current-node
887                                    root-address)))
888             (error "Already at root directory of current server")))
889       (error "Command invalid for this page"))))
890
891 (defun elpher-bookmarks-current-p ()
892   "Return non-nil if current node is a bookmarks page."
893   (eq (elpher-address-type (elpher-node-address elpher-current-node)) 'bookmarks))
894
895 (defun elpher-reload-bookmarks ()
896   "Reload bookmarks if current node is a bookmarks page."
897   (if (elpher-bookmarks-current-p)
898       (elpher-reload-current-node)))
899
900 (defun elpher-bookmark-current ()
901   "Bookmark the current node."
902   (interactive)
903   (unless (elpher-bookmarks-current-p)
904       (let ((address (elpher-node-address elpher-current-node))
905             (display-string (read-string "Bookmark display string: "
906                                          (elpher-node-display-string elpher-current-node))))
907         (elpher-add-address-bookmark address display-string)
908         (message "Bookmark added."))))
909
910 (defun elpher-bookmark-link ()
911   "Bookmark the link at point."
912   (interactive)
913   (let ((button (button-at (point))))
914     (if button
915         (let* ((node (button-get button 'elpher-node))
916                (address (elpher-node-address node))
917                (display-string (read-string "Bookmark display string: "
918                                             (elpher-node-display-string node))))
919           (elpher-add-address-bookmark address display-string)
920           (elpher-reload-bookmarks)
921           (message "Bookmark added."))
922       (error "No link selected"))))
923
924 (defun elpher-unbookmark-current ()
925   "Remove bookmark for the current node."
926   (interactive)
927   (unless (elpher-bookmarks-current-p)
928     (elpher-remove-address-bookmark (elpher-node-address elpher-current-node))
929     (message "Bookmark removed.")))
930
931 (defun elpher-unbookmark-link ()
932   "Remove bookmark for the link at point."
933   (interactive)
934   (let ((button (button-at (point))))
935     (if button
936         (let ((node (button-get button 'elpher-node)))
937           (elpher-remove-address-bookmark (elpher-node-address node))
938           (elpher-reload-bookmarks)
939           (message "Bookmark removed."))
940       (error "No link selected"))))
941
942 (defun elpher-bookmarks ()
943   "Visit bookmarks."
944   (interactive)
945   (switch-to-buffer "*elpher*")
946   (elpher-visit-node
947    (elpher-make-node "Bookmarks"
948                      elpher-current-node
949                      (elpher-make-address 'bookmarks))))
950
951 (defun elpher-info-node (node)
952   "Display information on NODE."
953   (let ((display-string (elpher-node-display-string node))
954         (address (elpher-node-address node)))
955     (if address
956         (message "`%s' on %s port %s"
957                 (elpher-address-selector address)
958                 (elpher-address-host address)
959                 (elpher-address-port address))
960       (message "%s" display-string))))
961
962 (defun elpher-info-link ()
963   "Display information on node corresponding to link at point."
964   (interactive)
965   (let ((button (button-at (point))))
966     (if button
967         (elpher-info-node (button-get button 'elpher-node))
968       (error "No item selected"))))
969   
970 (defun elpher-info-current ()
971   "Display information on current node."
972   (interactive)
973   (elpher-info-node elpher-current-node))
974
975 (defun elpher-get-address-url (address)
976   "Get URL representation of ADDRESS."
977   (concat "gopher://"
978           (elpher-address-host address)
979           (let ((port (elpher-address-port address)))
980             (if (equal port 70)
981                 ""
982               (format ":%d" port)))
983           "/" (string (elpher-address-type address))
984           (elpher-address-selector address)))
985
986 (defun elpher-copy-node-url (node)
987   "Copy URL representation of address of NODE to `kill-ring'."
988   (let ((address (elpher-node-address node)))
989     (if address
990         (let ((url (elpher-get-address-url address)))
991           (message url)
992           (kill-new url))
993       (error (format "Cannot represent %s as URL" (elpher-node-display-string node))))))
994
995 (defun elpher-copy-link-url ()
996   "Copy URL of item at point to `kill-ring'."
997   (interactive)
998   (let ((button (button-at (point))))
999     (if button
1000         (elpher-copy-node-url (button-get button 'elpher-node))
1001       (error "No item selected"))))
1002
1003 (defun elpher-copy-current-url ()
1004   "Copy URL of current node to `kill-ring'."
1005   (interactive)
1006   (elpher-copy-node-url elpher-current-node))
1007
1008 ;;; Mode and keymap
1009 ;;
1010
1011 (defvar elpher-mode-map
1012   (let ((map (make-sparse-keymap)))
1013     (define-key map (kbd "TAB") 'elpher-next-link)
1014     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1015     (define-key map (kbd "u") 'elpher-back)
1016     (define-key map (kbd "O") 'elpher-root-dir)
1017     (define-key map (kbd "g") 'elpher-go)
1018     (define-key map (kbd "r") 'elpher-redraw)
1019     (define-key map (kbd "R") 'elpher-reload)
1020     (define-key map (kbd "w") 'elpher-view-raw)
1021     (define-key map (kbd "d") 'elpher-download)
1022     (define-key map (kbd "m") 'elpher-jump)
1023     (define-key map (kbd "i") 'elpher-info-link)
1024     (define-key map (kbd "I") 'elpher-info-current)
1025     (define-key map (kbd "c") 'elpher-copy-link-url)
1026     (define-key map (kbd "C") 'elpher-copy-current-url)
1027     (define-key map (kbd "a") 'elpher-bookmark-link)
1028     (define-key map (kbd "A") 'elpher-bookmark-current)
1029     (define-key map (kbd "x") 'elpher-unbookmark-link)
1030     (define-key map (kbd "X") 'elpher-unbookmark-current)
1031     (define-key map (kbd "B") 'elpher-bookmarks)
1032     (when (fboundp 'evil-define-key)
1033       (evil-define-key 'motion map
1034         (kbd "TAB") 'elpher-next-link
1035         (kbd "C-]") 'elpher-follow-current-link
1036         (kbd "C-t") 'elpher-back
1037         (kbd "u") 'elpher-back
1038         (kbd "O") 'elpher-root-dir
1039         (kbd "g") 'elpher-go
1040         (kbd "r") 'elpher-redraw
1041         (kbd "R") 'elpher-reload
1042         (kbd "w") 'elpher-view-raw
1043         (kbd "d") 'elpher-download
1044         (kbd "m") 'elpher-jump
1045         (kbd "i") 'elpher-info-link
1046         (kbd "I") 'elpher-info-current
1047         (kbd "c") 'elpher-copy-link-url
1048         (kbd "C") 'elpher-copy-current-url
1049         (kbd "a") 'elpher-bookmark-link
1050         (kbd "A") 'elpher-bookmark-current
1051         (kbd "x") 'elpher-unbookmark-link
1052         (kbd "X") 'elpher-unbookmark-current
1053         (kbd "B") 'elpher-bookmarks))
1054     map)
1055   "Keymap for gopher client.")
1056
1057 (define-derived-mode elpher-mode special-mode "elpher"
1058   "Major mode for elpher, an elisp gopher client.")
1059
1060 (when (fboundp 'evil-set-initial-state)
1061   (evil-set-initial-state 'elpher-mode 'motion))
1062
1063 ;;; Main start procedure
1064 ;;
1065
1066 ;;;###autoload
1067 (defun elpher ()
1068   "Start elpher with default landing page."
1069   (interactive)
1070   (if (get-buffer "*elpher*")
1071       (switch-to-buffer "*elpher*")
1072     (switch-to-buffer "*elpher*")
1073     (setq elpher-current-node nil)
1074     (let ((start-node (elpher-make-node "Elpher Start Page" nil (elpher-make-address 'start))))
1075       (elpher-visit-node start-node)))
1076   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1077
1078 ;;; elpher.el ends here