Finished documenting functions.
[elpher.git] / elopher.el
1 ;;; elopher.el --- elisp gopher client
2
3 ;;; Commentary:
4
5 ;; An elisp gopher client.
6
7 ;;; Code:
8
9 ;;; Global constants
10 ;;
11
12 (defconst elopher-version "1.0.0"
13   "Current version of elopher.")
14
15 (defconst elopher-margin-width 6
16   "Width of left-hand margin used when rendering indicies.")
17
18 (defconst elopher-start-index
19   (mapconcat
20    'identity
21    (list "i\tfake\tfake\t1"
22          "i--------------------------------------------\tfake\tfake\t1"
23          "i          Elopher Gopher Client             \tfake\tfake\t1"
24          (format "i              version %s\tfake\tfake\t1" elopher-version)
25          "i--------------------------------------------\tfake\tfake\t1"
26          "i\tfake\tfake\t1"
27          "iBasic usage:\tfake\tfake\t1"
28          "i\tfake\tfake\t1"
29          "i - tab/shift-tab: next/prev directory entry on current page\tfake\tfake\t1"
30          "i - RET/mouse-1: open directory entry under cursor\tfake\tfake\t1"
31          "i - u: return to parent directory entry\tfake\tfake\t1"
32          "i - g: go to a particular page\tfake\tfake\t1"
33          "i - r: redraw current page (using cached contents if available)\tfake\tfake\t1"
34          "i - R: reload current page (regenerates cache)\tfake\tfake\t1"
35          "i - d: download directory entry under cursor\tfake\tfake\t1"
36          "i - w: display the raw server response for the current page\tfake\tfake\t1"
37          "i\tfake\tfake\t1"
38          "iPlaces to start exploring Gopherspace:\tfake\tfake\t1"
39          "i\tfake\tfake\t1"
40          "1Floodgap Systems Gopher Server\t\tgopher.floodgap.com\t70"
41          "i\tfake\tfake\t1"
42          "iAlternatively, select the following item and enter some\tfake\tfake\t1"
43          "isearch terms:\tfake\tfake\t1"
44          "i\tfake\tfake\t1"
45          "7Veronica-2 Gopher Search Engine\t/v2/vs\tgopher.floodgap.com\t70"
46          ".")
47    "\r\n")
48   "Source for elopher start page.")
49
50
51 ;;; Customization group
52 ;;
53
54 (defgroup elopher nil
55   "A gopher client."
56   :group 'applications)
57
58 (defface elopher-index
59   '((((background dark)) :foreground "deep sky blue")
60     (((background light)) :foreground "blue"))
61   "Face used for index records.")
62
63 (defface elopher-text
64   '((((background dark)) :foreground "white")
65     (((background light)) :weight bold))
66   "Face used for text records.")
67
68 (defface elopher-info '()
69   "Face used for info records.")
70
71 (defface elopher-image
72   '((((background dark)) :foreground "green")
73     (t :foreground "dark green"))
74   "Face used for image records.")
75
76 (defface elopher-search
77   '((((background light)) :foreground "orange")
78     (((background dark)) :foreground "dark orange"))
79   "Face used for search records.")
80
81 (defface elopher-url
82   '((((background dark)) :foreground "yellow")
83     (((background light)) :foreground "dark red"))
84   "Face used for url records.")
85
86 (defface elopher-binary
87   '((t :foreground "magenta"))
88   "Face used for binary records.")
89
90 (defface elopher-unknown
91   '((t :foreground "red"))
92   "Face used for unknown record types.")
93
94 (defface elopher-margin-key
95   '((((background dark)) :foreground "white"))
96   "Face used for margin key.")
97
98 (defface elopher-margin-brackets
99   '((t :foreground "blue"))
100   "Face used for brackets around margin key.")
101
102 (defcustom elopher-open-urls-with-eww nil
103   "If non-nil, open URL selectors using eww.
104 Otherwise, use the system browser via the BROWSE-URL function."
105   :type '(boolean))
106
107 ;;; Model
108 ;;
109
110 ;; Address
111
112 (defun elopher-make-address (selector host port)
113   "Create an address of a gopher object with SELECTOR, HOST and PORT."
114   (list selector host port))
115
116 (defun elopher-address-selector (address)
117   "Retrieve selector from ADDRESS."
118   (car address))
119
120 (defun elopher-address-host (address)
121   "Retrieve host from ADDRESS."
122   (cadr address))
123
124 (defun elopher-address-port (address)
125   "Retrieve port from ADDRESS."
126   (caddr address))
127
128 ;; Node
129
130 (defun elopher-make-node (parent address getter &optional content pos)
131   "Create a node in the gopher page hierarchy.
132
133 PARENT specifies the parent of the node, ADDRESS specifies the address of
134 the gopher page, GETTER provides the getter function used to obtain this
135 page.
136
137 The optional arguments CONTENT and POS can be used to fill the cached
138 content and cursor position fields of the node."
139   (list parent address getter content pos))
140
141 (defun elopher-node-parent (node)
142   "Retrieve the parent node of NODE."
143   (elt node 0))
144
145 (defun elopher-node-address (node)
146   "Retrieve the address of NODE."
147   (elt node 1))
148
149 (defun elopher-node-getter (node)
150   "Retrieve the preferred getter function of NODE."
151   (elt node 2))
152
153 (defun elopher-node-content (node)
154   "Retrieve the cached content of NODE, or nil if none exists."
155   (elt node 3))
156
157 (defun elopher-node-pos (node)
158   "Retrieve the cached cursor position for NODE, or nil if none exists."
159   (elt node 4))
160
161 (defun elopher-set-node-content (node content)
162   "Set the content cache of NODE to CONTENT."
163   (setcar (nthcdr 3 node) content))
164
165 (defun elopher-set-node-pos (node pos)
166   "Set the cursor position cache of NODE to POS."
167   (setcar (nthcdr 4 node) pos))
168
169 (defun elopher-save-pos ()
170   "Save the current position of point to the current node."
171   (when elopher-current-node
172     (elopher-set-node-pos elopher-current-node (point))))
173
174 (defun elopher-restore-pos ()
175   "Restore the position of point to that cached in the current node."
176   (let ((pos (elopher-node-pos elopher-current-node)))
177     (if pos
178         (goto-char pos)
179       (goto-char (point-min)))))
180
181 ;; Node graph traversal
182
183 (defvar elopher-current-node)
184
185 (defun elopher-visit-node (node &optional getter)
186   "Visit NODE using its own getter or GETTER, if non-nil."
187   (elopher-save-pos)
188   (elopher-process-cleanup)
189   (setq elopher-current-node node)
190   (if getter
191       (funcall getter)
192     (funcall (elopher-node-getter node))))
193
194 (defun elopher-visit-parent-node ()
195   "Visit the parent of the current node."
196   (let ((parent-node (elopher-node-parent elopher-current-node)))
197     (when parent-node
198       (elopher-visit-node parent-node))))
199       
200 (defun elopher-reload-current-node ()
201   "Reload the current node, discarding any existing cached content."
202   (elopher-set-node-content elopher-current-node nil)
203   (elopher-visit-node elopher-current-node))
204
205 ;;; Buffer preparation
206 ;;
207
208 (defmacro elopher-with-clean-buffer (&rest args)
209   "Evaluate ARGS with a clean *elopher* buffer as current."
210   (list 'progn
211         '(switch-to-buffer "*elopher*")
212         '(elopher-mode)
213         (append (list 'let '((inhibit-read-only t))
214                       '(erase-buffer))
215                 args)))
216
217 ;;; Index rendering
218 ;;
219
220 (defun elopher-insert-index (string)
221   "Insert the index corresponding to STRING into the current buffer."
222   (dolist (line (split-string string "\r\n"))
223     (unless (= (length line) 0)
224       (elopher-insert-index-record line))))
225
226 (defun elopher-insert-margin (&optional type-name)
227   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
228   (if type-name
229       (progn
230         (insert (format (concat "%" (number-to-string (- elopher-margin-width 1)) "s")
231                         (concat
232                          (propertize "[" 'face 'elopher-margin-brackets)
233                          (propertize type-name 'face 'elopher-margin-key)
234                          (propertize "]" 'face 'elopher-margin-brackets))))
235         (insert " "))
236     (insert (make-string elopher-margin-width ?\s))))
237
238 (defvar elopher-type-map
239   '((?0 elopher-get-text-node "T" elopher-text)
240     (?1 elopher-get-index-node "/" elopher-index)
241     (?g elopher-get-image-node "im" elopher-image)
242     (?p elopher-get-image-node "im" elopher-image)
243     (?I elopher-get-image-node "im" elopher-image)
244     (?4 elopher-get-node-download "B" elopher-binary)
245     (?5 elopher-get-node-download "B" elopher-binary)
246     (?9 elopher-get-node-download "B" elopher-binary)
247     (?7 elopher-get-search-node "?" elopher-search))
248   "Association list from types to getters, margin codes and index faces.")
249
250 (defun elopher-insert-index-record (line)
251   "Insert the index record corresponding to LINE into the current buffer."
252   (let* ((type (elt line 0))
253          (fields (split-string (substring line 1) "\t"))
254          (display-string (elt fields 0))
255          (selector (elt fields 1))
256          (host (elt fields 2))
257          (port (elt fields 3))
258          (address (elopher-make-address selector host port))
259          (type-map-entry (alist-get type elopher-type-map)))
260     (if type-map-entry
261         (let ((getter (car type-map-entry))
262               (margin-code (cadr type-map-entry))
263               (face (caddr type-map-entry)))
264           (elopher-insert-margin margin-code)
265           (insert-text-button display-string
266                               'face face
267                               'elopher-node (elopher-make-node elopher-current-node
268                                                                address
269                                                                getter)
270                               'action #'elopher-click-link
271                               'follow-link t
272                               'help-echo (format "mouse-1, RET: open %s on %s port %s"
273                                                  selector host port)))
274       (pcase type
275         (?i (elopher-insert-margin) ; Information
276             (insert (propertize display-string
277                                 'face 'elopher-info)))
278         (?h (elopher-insert-margin "W") ; Web link
279             (let ((url (elt (split-string selector "URL:") 1)))
280               (insert-text-button display-string
281                                   'face 'elopher-url
282                                   'elopher-url url
283                                   'action #'elopher-click-url
284                                   'follow-link t
285                                   'help-echo (format "mouse-1, RET: open url %s" url))))
286         (?.) ; Occurs at end of index, can safely ignore.
287         (tp (elopher-insert-margin (concat (char-to-string tp) "?"))
288             (insert (propertize display-string
289                                 'face 'elopher-unknown-face)))))
290     (insert "\n")))
291
292
293 ;;; Selector retrieval (all kinds)
294 ;;
295
296 (defun elopher-process-cleanup ()
297   "Immediately shut down any extant elopher process."
298   (let ((p (get-process "elopher-process")))
299     (if p (delete-process p))))
300
301 (defvar elopher-selector-string)
302
303 (defun elopher-get-selector (address after)
304   "Retrieve selector specified by ADDRESS, then execute AFTER.
305 The result is stored as a string in the variable elopher-selector-string."
306   (setq elopher-selector-string "")
307   (make-network-process
308    :name "elopher-process"
309    :host (elopher-address-host address)
310    :service (elopher-address-port address)
311    :filter (lambda (proc string)
312              (setq elopher-selector-string (concat elopher-selector-string string)))
313    :sentinel after)
314   (process-send-string "elopher-process"
315                        (concat (elopher-address-selector address) "\n")))
316
317 ;; Index retrieval
318
319 (defun elopher-get-index-node ()
320   "Getter which retrieves the current node contents as an index."
321   (let ((content (elopher-node-content elopher-current-node))
322         (address (elopher-node-address elopher-current-node)))
323     (if content
324         (progn
325           (elopher-with-clean-buffer
326            (insert content))
327           (elopher-restore-pos))
328       (if address
329           (progn
330             (elopher-with-clean-buffer
331              (insert "LOADING DIRECTORY..."))
332             (elopher-get-selector address
333                                   (lambda (proc event)
334                                     (unless (string-prefix-p "deleted" event)
335                                       (elopher-with-clean-buffer
336                                        (elopher-insert-index elopher-selector-string))
337                                       (elopher-restore-pos)
338                                       (elopher-set-node-content elopher-current-node
339                                                                 (buffer-string))))))
340         (progn
341           (elopher-with-clean-buffer
342            (elopher-insert-index elopher-start-index))
343           (elopher-restore-pos)
344           (elopher-set-node-content elopher-current-node
345                                     (buffer-string)))))))
346
347 ;; Text retrieval
348
349 (defconst elopher-url-regex
350   "\\(https?\\|gopher\\)://\\([a-zA-Z0-9.\-]+\\)\\(?3::[0-9]+\\)?\\(?4:/[^ \r\n\t(),]*\\)?"
351   "Regexp used to locate and buttinofy URLs in text files loaded by elopher.")
352
353 (defun elopher-buttonify-urls (string)
354   "Turn substrings which look like urls in STRING into clickable buttons."
355   (with-temp-buffer
356     (insert string)
357     (goto-char (point-min))
358     (while (re-search-forward elopher-url-regex nil t)
359       (let ((url (match-string 0))
360             (protocol (downcase (match-string 1))))
361         (if (string= protocol "gopher")
362             (let* ((host (match-string 2))
363                    (port 70)
364                    (type-and-selector (match-string 4))
365                    (type (if (> (length type-and-selector) 1)
366                              (elt type-and-selector 1)
367                            ?1))
368                    (selector (if (> (length type-and-selector) 1)
369                                  (substring type-and-selector 2)
370                                ""))
371                    (address (elopher-make-address selector host port))
372                    (getter (car (alist-get type elopher-type-map))))
373               (make-text-button (match-beginning 0)
374                                 (match-end 0)
375                                 'elopher-node (elopher-make-node elopher-current-node
376                                                                  address
377                                                                  getter)
378                                 'action #'elopher-click-link
379                                 'follow-link t
380                                 'help-echo (format "mouse-1, RET: open %s on %s port %s"
381                                                    selector host port)))
382           (make-text-button (match-beginning 0)
383                             (match-end 0)
384                             'elopher-url url
385                             'action #'elopher-click-url
386                             'follow-link t
387                             'help-echo (format "mouse-1, RET: open url %s" url)))))
388     (buffer-string)))
389
390 (defun elopher-process-text (string)
391   "Remove CRs and trailing period from the gopher text document STRING."
392   (let* ((chopped-str (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
393          (cleaned-str (replace-regexp-in-string "\r" "" chopped-str)))
394     (elopher-buttonify-urls cleaned-str)))
395
396 (defun elopher-get-text-node ()
397   "Getter which retrieves the current node contents as a text document."
398   (let ((content (elopher-node-content elopher-current-node))
399         (address (elopher-node-address elopher-current-node)))
400     (if content
401         (progn
402           (elopher-with-clean-buffer
403            (insert content))
404           (elopher-restore-pos))
405       (progn
406         (elopher-with-clean-buffer
407          (insert "LOADING TEXT..."))
408         (elopher-get-selector address
409                               (lambda (proc event)
410                                 (unless (string-prefix-p "deleted" event)
411                                   (elopher-with-clean-buffer
412                                    (insert (elopher-process-text elopher-selector-string)))
413                                   (elopher-restore-pos)
414                                   (elopher-set-node-content elopher-current-node
415                                                             (buffer-string)))))))))
416
417 ;; Image retrieval
418
419 (defun elopher-get-image-node ()
420   "Getter which retrieves the current node contents as an image to view."
421   (let ((content (elopher-node-content elopher-current-node))
422         (address (elopher-node-address elopher-current-node)))
423     (if content
424         (progn
425           (elopher-with-clean-buffer
426            (insert-image content))
427           (setq cursor-type nil)
428           (elopher-restore-pos))
429       (progn
430         (elopher-with-clean-buffer
431          (insert "LOADING IMAGE..."))
432         (elopher-get-selector address
433                               (lambda (proc event)
434                                 (unless (string-prefix-p "deleted" event)
435                                   (let ((image (create-image
436                                                 (string-as-unibyte elopher-selector-string)
437                                                 nil t)))
438                                     (elopher-with-clean-buffer
439                                      (insert-image image))
440                                     (setq cursor-type nil)
441                                     (elopher-restore-pos)
442                                     (elopher-set-node-content elopher-current-node
443                                                               image)))))))))
444
445 ;; Search retrieval
446
447 (defun elopher-get-search-node ()
448   "Getter which submits a search query to the address of the current node."
449   (let ((content (elopher-node-content elopher-current-node))
450         (address (elopher-node-address elopher-current-node))
451         (aborted t))
452     (if content
453         (progn
454           (elopher-with-clean-buffer
455            (insert content))
456           (elopher-restore-pos)
457           (message "Displaying cached search results.  Reload to perform a new search."))
458       (unwind-protect
459           (let* ((query-string (read-string "Query: "))
460                  (query-selector (concat (elopher-address-selector address) "\t" query-string))
461                  (search-address (elopher-make-address query-selector
462                                                        (elopher-address-host address)
463                                                        (elopher-address-port address))))
464             (setq aborted nil)
465             (elopher-with-clean-buffer
466              (insert "LOADING RESULTS..."))
467             (elopher-get-selector search-address
468                                   (lambda (proc event)
469                                     (unless (string-prefix-p "deleted" event)
470                                       (elopher-with-clean-buffer
471                                        (elopher-insert-index elopher-selector-string))
472                                       (goto-char (point-min))
473                                       (elopher-set-node-content elopher-current-node
474                                                                 (buffer-string))))))
475         (if aborted
476             (elopher-visit-parent-node))))))
477
478 ;; Raw server response retrieval
479
480 (defun elopher-get-node-raw ()
481   "Getter which retrieves the raw server response for the current node."
482   (let* ((content (elopher-node-content elopher-current-node))
483          (address (elopher-node-address elopher-current-node)))
484     (elopher-with-clean-buffer
485      (insert "LOADING RAW SERVER RESPONSE..."))
486     (if address
487         (elopher-get-selector address
488                               (lambda (proc event)
489                                 (unless (string-prefix-p "deleted" event)
490                                   (elopher-with-clean-buffer
491                                    (insert elopher-selector-string))
492                                   (goto-char (point-min)))))
493       (progn
494         (elopher-with-clean-buffer
495          (insert elopher-start-index))
496         (goto-char (point-min)))))
497   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
498  
499 ;; File export retrieval
500
501 (defvar elopher-download-filename)
502
503 (defun elopher-get-node-download ()
504   "Getter which retrieves the current node and writes the result to a file."
505   (let* ((address (elopher-node-address elopher-current-node))
506          (selector (elopher-address-selector address)))
507     (elopher-visit-parent-node) ; Do first in case of non-local exits.
508     (let* ((filename-proposal (file-name-nondirectory selector))
509            (filename (read-file-name "Save file as: "
510                                      nil nil nil
511                                      (if (> (length filename-proposal) 0)
512                                          filename-proposal
513                                        "gopher.file"))))
514       (message "Downloading...")
515       (setq elopher-download-filename filename)
516       (elopher-get-selector address
517                             (lambda (proc event)
518                               (let ((coding-system-for-write 'binary))
519                                 (with-temp-file elopher-download-filename
520                                   (insert elopher-selector-string)
521                                   (message (format "Download complate, saved to file %s."
522                                                    elopher-download-filename)))))))))
523
524
525 ;;; Navigation procedures
526 ;;
527
528 (defun elopher-next-link ()
529   "Move point to the next link on the current page."
530   (interactive)
531   (forward-button 1))
532
533 (defun elopher-prev-link ()
534   "Move point to the previous link on the current page."
535   (interactive)
536   (backward-button 1))
537
538 (defun elopher-click-link (button)
539   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
540   (let ((node (button-get button 'elopher-node)))
541     (elopher-visit-node node)))
542
543 (defun elopher-click-url (button)
544   "Function called when the url link BUTTON is activated (via mouse or keypress)."
545   (let ((url (button-get button 'elopher-url)))
546     (if elopher-open-urls-with-eww
547         (browse-web url)
548       (browse-url url))))
549
550 (defun elopher-follow-current-link ()
551   "Open the link or url at point."
552   (interactive)
553   (push-button))
554
555 (defun elopher-go ()
556   "Go to a particular gopher site."
557   (interactive)
558   (let* (
559          (hostname (read-string "Gopher host: "))
560          (selector (read-string "Selector (default none): " nil nil ""))
561          (port (read-string "Port (default 70): " nil nil 70))
562          (address (list selector hostname port)))
563     (elopher-visit-node
564      (elopher-make-node elopher-current-node
565                         address
566                         #'elopher-get-index-node))))
567
568 (defun  elopher-redraw ()
569   "Redraw current page."
570   (interactive)
571   (elopher-visit-node elopher-current-node))
572
573 (defun  elopher-reload ()
574   "Reload current page."
575   (interactive)
576   (elopher-reload-current-node))
577
578 (defun elopher-view-raw ()
579   "View current page as plain text."
580   (interactive)
581   (elopher-visit-node elopher-current-node
582                       #'elopher-get-node-raw))
583
584 (defun elopher-back ()
585   "Go to previous site."
586   (interactive)
587   (if (elopher-node-parent elopher-current-node)
588       (elopher-visit-parent-node)
589     (message "No previous site.")))
590
591 (defun elopher-download ()
592   "Download the link at point."
593   (interactive)
594   (let ((button (button-at (point))))
595     (if button
596         (let ((node (button-get button 'elopher-node)))
597           (if node
598               (elopher-visit-node (button-get button 'elopher-node)
599                                   #'elopher-get-node-download)
600             (message "Can only download gopher links, not general URLs.")))
601       (message "No link selected."))))
602
603 ;;; Mode and keymap
604 ;;
605
606 (defvar elopher-mode-map
607   (let ((map (make-sparse-keymap)))
608     (define-key map (kbd "TAB") 'elopher-next-link)
609     (define-key map (kbd "<backtab>") 'elopher-prev-link)
610     (define-key map (kbd "u") 'elopher-back)
611     (define-key map (kbd "g") 'elopher-go)
612     (define-key map (kbd "r") 'elopher-redraw)
613     (define-key map (kbd "R") 'elopher-reload)
614     (define-key map (kbd "w") 'elopher-view-raw)
615     (define-key map (kbd "d") 'elopher-download)
616     (when (fboundp 'evil-define-key)
617       (evil-define-key 'normal map
618         (kbd "TAB") 'elopher-next-link
619         (kbd "C-]") 'elopher-follow-current-link
620         (kbd "C-t") 'elopher-back
621         (kbd "u") 'elopher-back
622         (kbd "g") 'elopher-go
623         (kbd "r") 'elopher-redraw
624         (kbd "R") 'elopher-reload
625         (kbd "w") 'elopher-view-raw
626         (kbd "d") 'elopher-download))
627     map)
628   "Keymap for gopher client.")
629
630 (define-derived-mode elopher-mode special-mode "elopher"
631   "Major mode for elopher, an elisp gopher client.")
632
633
634 ;;; Main start procedure
635 ;;
636
637 (defun elopher ()
638   "Start elopher with default landing page."
639   (interactive)
640   (setq elopher-current-node nil)
641   (let ((start-node (elopher-make-node nil nil #'elopher-get-index-node)))
642     (elopher-visit-node start-node))
643   "Started Elopher.") ; Otherwise (elopher) evaluates to start page string.
644
645 ;;; elopher.el ends here