Can now erase context output.
[lurk.git] / lurk.el
1 ;;; lurk.el --- Little Unibuffer iRc Klient -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2021 Tim Vaughan
4
5 ;; Author: Tim Vaughan <timv@ughan.xyz>
6 ;; Created: 14 June 2021
7 ;; Version: 1.0
8 ;; Keywords: network
9 ;; Homepage: http://thelambdalab.xyz/lurk
10 ;; Package-Requires: ((emacs "26"))
11
12 ;; This file is not part of GNU Emacs.
13
14 ;; This program is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 (provide 'lurk)
32
33
34 ;;; Customizations
35 ;;
36
37 (defgroup lurk nil
38   "Little Unibuffer iRc Klient."
39   :group 'network)
40
41 (defcustom lurk-nick "plugd"
42   "Default nick.")
43
44 (defcustom lurk-default-quit-msg "Bye"
45   "Default quit message when none supplied.")
46
47 (defcustom lurk-networks
48   '(("libera" "irc.libera.chat" 6697))
49   "IRC networks.")
50
51 (defcustom lurk-allow-ipv6 nil
52   "Set to non-nil to allow use of IPv6.")
53
54 (defcustom lurk-show-joins nil
55   "Set to non-nil to be notified of joins, parts and quits.")
56
57 (defcustom lurk-display-header t
58   "If non-nil, use buffer header to display information on current host and channel.")
59
60 ;;; Faces
61 ;;
62
63 (defface lurk-text
64   '((t :inherit default))
65   "Face used for Lurk text.")
66
67 (defface lurk-prompt
68   '((t :inherit font-lock-keyword-face))
69   "Face used for the prompt.")
70
71 (defface lurk-context
72   '((t :inherit lurk-context))
73   "Face used for the context name in the prompt.")
74
75 (defface lurk-faded
76   '((t :inherit shadow))
77   "Face used for faded Lurk text.")
78
79 (defface lurk-timestamp
80   '((t :inherit shadow))
81   "Face used for timestamps.")
82
83 (defface lurk-error
84   '((t :inherit error))
85   "Face used for Lurk error text.")
86
87 (defface lurk-notice
88   '((t :inherit warning))
89   "Face used for Lurk notice text.")
90
91 ;;; Global variables
92 ;;
93
94 (defvar lurk-version "Lurk v0.1"
95   "Value of this string is used in response to CTCP version queries.")
96
97 (defvar lurk-notice-prefix "-!-")
98
99 (defvar lurk-error-prefix "!!!")
100
101 (defvar lurk-prompt-string ">")
102
103 (defvar lurk-debug nil
104   "If non-nil, enable debug mode.")
105
106
107 ;;; Utility procedures
108 ;;
109
110 (defun lurk--filtered-join (&rest args)
111   (string-join (seq-filter (lambda (el) el) args) " "))
112
113 (defun lurk--as-string (obj)
114   (if obj
115       (with-output-to-string (princ obj))
116     nil))
117
118
119 ;;; Network process
120 ;;
121
122 (defvar lurk-response "")
123
124 (defun lurk-filter (proc string)
125   (dolist (line (split-string (concat lurk-response string) "\n"))
126     (if (string-suffix-p "\r" line)
127         (lurk-eval-msg-string (string-trim line))
128       (setq lurk-response line))))
129
130 (defun lurk-sentinel (proc string)
131   (unless (equal "open" (string-trim string))
132     (lurk-display-error "Disconnected from server.")
133     (clrhash lurk-contexts)
134     (lurk-set-current-context nil)
135     (lurk-render-prompt)
136     (cancel-timer lurk-ping-timer)))
137
138 (defun lurk-start-process (network)
139   (let* ((row (assoc network lurk-networks))
140          (host (elt row 1))
141          (port (elt row 2))
142          (flags (seq-drop row 3)))
143     (make-network-process :name "lurk"
144                           :host host
145                           :service port
146                           :family (if lurk-allow-ipv6 nil 'ipv4)
147                           :filter #'lurk-filter
148                           :sentinel #'lurk-sentinel
149                           :nowait nil
150                           :tls-parameters (if (memq :notls flags)
151                                               nil
152                                             (cons 'gnutls-x509pki
153                                                   (gnutls-boot-parameters
154                                                    :type 'gnutls-x509pki
155                                                    :hostname host)))
156                           :buffer "*lurk*")))
157
158 (defvar lurk-ping-timer nil)
159 (defvar lurk-ping-period 60)
160
161 (defun lurk-ping-function ()
162   (lurk-send-msg (lurk-msg nil nil "PING" (car (process-contact (get-process "lurk")))))
163   (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))
164
165 (defun lurk-connect (network)
166   (if (get-process "lurk")
167       (lurk-display-error "Already connected.  Disconnect first.")
168     (if (not (assoc network lurk-networks))
169         (lurk-display-error "Network '" network "' is unknown.")
170       (clrhash lurk-contexts)
171       (lurk-set-current-context nil)
172       (lurk-start-process network)
173       (lurk-send-msg (lurk-msg nil nil "USER" lurk-nick 0 "*" lurk-nick))
174       (lurk-send-msg (lurk-msg nil nil "NICK" lurk-nick))
175       (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))))
176
177 (defun lurk-connected-p ()
178   (let ((proc (get-process "lurk")))
179     (and proc (eq (process-status proc) 'open))))
180
181 (defun lurk-send-msg (msg)
182   (if lurk-debug
183       (lurk-display-string nil nil (lurk-msg->string msg)))
184   (let ((proc (get-process "lurk")))
185     (if (and proc (eq (process-status proc) 'open))
186         (process-send-string proc (concat (lurk-msg->string msg) "\r\n"))
187       (lurk-display-error "No server connection established.")
188       (error "No server connection established"))))
189
190
191 ;;; Server messages
192 ;;
193
194 (defun lurk-msg (tags src cmd &rest params)
195   (list (lurk--as-string tags)
196         (lurk--as-string src)
197         (upcase (lurk--as-string cmd))
198         (mapcar #'lurk--as-string
199                 (if (and params (listp (elt params 0)))
200                     (elt params 0)
201                   params))))
202
203 (defun lurk-msg-tags (msg) (elt msg 0))
204 (defun lurk-msg-src (msg) (elt msg 1))
205 (defun lurk-msg-cmd (msg) (elt msg 2))
206 (defun lurk-msg-params (msg) (elt msg 3))
207 (defun lurk-msg-trail (msg)
208   (let ((params (lurk-msg-params msg)))
209     (if params
210         (elt params (- (length params) 1)))))
211
212 (defvar lurk-msg-regex
213   (rx
214    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
215         (* whitespace))
216    (opt (: ":" (: (group (* (not (any space "!" "@"))))
217                   (* (not (any space)))))
218         (* whitespace))
219    (group (: (* (not whitespace))))
220    (* whitespace)
221    (opt (group (+ not-newline))))
222   "Regex used to parse IRC messages.
223 Note that this regex is incomplete.  Noteably, we discard the non-nick
224 portion of the source component of the message, as LURK doesn't use this.")
225
226 (defun lurk-string->msg (string)
227   (if (string-match lurk-msg-regex string)
228       (let* ((tags (match-string 1 string))
229              (src (match-string 2 string))
230              (cmd (upcase (match-string 3 string)))
231              (params-str (match-string 4 string))
232              (params
233               (if params-str
234                   (let* ((idx (cl-search ":" params-str))
235                          (l (split-string (string-trim (substring params-str 0 idx))))
236                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
237                     (append l r))
238                 nil)))
239         (apply #'lurk-msg (append (list tags src cmd) params)))
240     (error "Failed to parse string " string)))
241
242 (defun lurk-msg->string (msg)
243   (let ((tags (lurk-msg-tags msg))
244         (src (lurk-msg-src msg))
245         (cmd (lurk-msg-cmd msg))
246         (params (lurk-msg-params msg)))
247     (lurk--filtered-join
248      (if tags (concat "@" tags) nil)
249      (if src (concat ":" src) nil)
250      cmd
251      (if (> (length params) 1)
252          (string-join (seq-take params (- (length params) 1)) " ")
253        nil)
254      (if (> (length params) 0)
255          (concat ":" (elt params (- (length params) 1)))
256        nil))))
257
258
259 ;;; Contexts
260 ;;
261
262 (defvar lurk-current-context nil)
263 (defvar lurk-contexts (make-hash-table :test #'equal))
264
265 (defun lurk-add-context (name)
266   (puthash name nil lurk-contexts))
267
268 (defun lurk-del-context (name)
269   (remhash name lurk-contexts))
270
271 (defun lurk-get-context-users (name)
272   (gethash name lurk-contexts))
273
274 (defun lurk-context-known-p (name)
275   (not (eq (gethash name lurk-contexts 0) 0)))
276
277 (defun lurk-add-context-users (context users)
278   (puthash context
279            (cl-union users
280                      (gethash context lurk-contexts))
281            lurk-contexts))
282
283 (defun lurk-del-context-user (context user)
284   (puthash context
285            (remove user (gethash context lurk-contexts))
286            lurk-contexts))
287
288 (defun lurk-del-user (user)
289   (dolist (context (lurk-get-context-list))
290     (lurk-del-context-user context user)))
291
292 (defun lurk-rename-user (old-nick new-nick)
293   (dolist (context (lurk-get-context-list))
294     (lurk-del-context-user context old-nick)
295     (lurk-add-context-users context (list new-nick))))
296
297 (defun lurk-get-context-type (name)
298   (cond
299    ((string-prefix-p "#" name) 'channel)
300    ((string-match-p (rx (or "." "localhost")) name) 'host)
301    (t 'nick)))
302
303 (defun lurk-get-context-list ()
304   (let ((res nil))
305     (maphash (lambda (key val)
306                (cl-pushnew key res))
307              lurk-contexts)
308     res))
309
310 (defun lurk-get-next-context (&optional prev)
311   (if lurk-current-context
312       (let* ((context-list (if prev
313                                (reverse (lurk-get-context-list))
314                              (lurk-get-context-list)))
315              (context-list* (member lurk-current-context context-list)))
316         (if (> (length context-list*) 1)
317             (cadr context-list*)
318           (car context-list)))
319     nil))
320
321 (defun lurk-set-current-context (context)
322   (setq lurk-current-context context)
323   (lurk-highlight-context context)
324   (if lurk-zoomed
325       (lurk-zoom-in lurk-current-context)))
326
327 (defun lurk-cycle-contexts (&optional rev)
328   (if lurk-current-context
329       (progn
330         (lurk-set-current-context (lurk-get-next-context rev))
331         (lurk-render-prompt))
332     (lurk-display-error "No channels joined.")))
333
334
335 ;;; Buffer
336 ;;
337
338 (defun lurk-render-prompt ()
339   (with-current-buffer "*lurk*"
340     (let ((update-point (= lurk-input-marker (point)))
341           (update-window-points (mapcar (lambda (w)
342                                           (list (= (window-point w) lurk-input-marker)
343                                                 w))
344                                         (get-buffer-window-list nil nil t))))
345       (save-excursion
346         (set-marker-insertion-type lurk-prompt-marker nil)
347         (set-marker-insertion-type lurk-input-marker t)
348         (let ((inhibit-read-only t))
349           (delete-region lurk-prompt-marker lurk-input-marker)
350           (goto-char lurk-prompt-marker)
351           (insert
352            (propertize (if lurk-current-context
353                            lurk-current-context
354                          "")
355                        'face 'lurk-context
356                        'read-only t)
357            (propertize lurk-prompt-string
358                        'face 'lurk-prompt
359                        'read-only t)
360            (propertize " " ; Need this to be separate to mark it as rear-nonsticky
361                        'read-only t
362                        'rear-nonsticky t)))
363         (set-marker-insertion-type lurk-input-marker nil))
364       (if update-point
365           (goto-char lurk-input-marker))
366       (dolist (v update-window-points)
367         (if (car v)
368             (set-window-point (cadr v) lurk-input-marker))))))
369   
370 (defvar lurk-prompt-marker nil
371   "Marker for prompt position in LURK buffer.")
372
373 (defvar lurk-input-marker nil
374   "Marker for prompt position in LURK buffer.")
375
376 (defun lurk-setup-header ()
377   (with-current-buffer "*lurk*"
378     (setq-local header-line-format
379                 '((:eval
380                    (let ((proc (get-process "lurk")))
381                      (if proc
382                          (concat
383                           "Host: " (car (process-contact proc))
384                           ", Context: "
385                           (if lurk-current-context
386                               (concat
387                                lurk-current-context
388                                " ("
389                                (number-to-string
390                                 (length (lurk-get-context-users lurk-current-context)))
391                                " users)")
392                             "Server"))
393                        "No connection")))
394                   (:eval
395                    (if lurk-zoomed " [ZOOMED]" ""))))))
396
397 (defun lurk-setup-buffer ()
398   (with-current-buffer (get-buffer-create "*lurk*")
399     (setq-local scroll-conservatively 1)
400     (setq-local buffer-invisibility-spec nil)
401     (if (markerp lurk-prompt-marker)
402         (set-marker lurk-prompt-marker (point-max))
403       (setq lurk-prompt-marker (point-max-marker)))
404     (if (markerp lurk-input-marker)
405         (set-marker lurk-input-marker (point-max))
406       (setq lurk-input-marker (point-max-marker)))
407     (goto-char (point-max))
408     (lurk-render-prompt)
409     (if lurk-display-header
410         (lurk-setup-header))))
411
412 (defun lurk-clear-buffer ()
413   "Completely erase all non-prompt and non-input text from lurk buffer."
414   (with-current-buffer "*lurk*"
415     (let ((inhibit-read-only t))
416       (delete-region (point-min) lurk-prompt-marker))))
417
418 ;;; Output formatting and highlighting
419 ;;
420
421 ;; Idea: the face text property can be a list of faces, applied in
422 ;; order.  By assigning each context a unique list and keeping track
423 ;; of these in a hash table, we can easily switch the face
424 ;; corresponding to a particular context by modifying the elements of
425 ;; this list.
426 ;;
427 ;; More subtly, we make only the cdrs of this list shared among
428 ;; all text of a given context, allowing the cars to be different
429 ;; and for different elements of the context-specific text to have
430 ;; different styling.
431
432 ;; Additionally, we allow selective hiding of contexts via
433 ;; the buffer-invisibility-spec.
434
435 (defvar lurk-context-facelists (make-hash-table :test 'equal)
436   "List of seen contexts and associated face lists.")
437
438 (defun lurk-get-context-facelist (context)
439   (let ((facelist (gethash context lurk-context-facelists)))
440     (unless facelist
441       (setq facelist (list 'lurk-text))
442       (puthash context facelist lurk-context-facelists))
443     facelist))
444
445 (defun lurk--fill-strings (col indent &rest strings)
446   (with-temp-buffer
447     (setq buffer-invisibility-spec nil)
448     (let ((fill-column col)
449           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
450       (apply #'insert strings)
451       (fill-region (point-min) (point-max) nil t)
452       (buffer-string))))
453
454 (defun lurk--start-of-final-line ()
455   (with-current-buffer "*lurk*"
456     (save-excursion
457       (goto-char (point-max))
458       (line-beginning-position))))
459
460 (defun lurk-scroll-windows-to-last-line ()
461   (with-current-buffer "*lurk*"
462     (dolist (window (get-buffer-window-list))
463       (if (>= (window-point window) (lurk--start-of-final-line))
464           (with-selected-window window
465             (recenter -1))))))
466
467 (defun lurk-display-string (context prefix &rest strings)
468   (with-current-buffer "*lurk*"
469     (save-excursion
470       (goto-char lurk-prompt-marker)
471       (let* ((inhibit-read-only t)
472              (old-pos (marker-position lurk-prompt-marker))
473              (padded-timestamp (concat (format-time-string "%H:%M ")))
474              (padded-prefix (if prefix (concat prefix " ") ""))
475              (context-atom (if context (intern context) nil)))
476         (insert-before-markers
477          (lurk--fill-strings
478           80
479           (+ (length padded-timestamp)
480              (length padded-prefix))
481           (propertize padded-timestamp
482                       'face 'lurk-timestamp
483                       'read-only t
484                       'context context
485                       'invisible context-atom)
486           (propertize padded-prefix
487                       'read-only t
488                       'context context
489                       'invisible context-atom)
490           (lurk-add-formatting
491            (propertize (concat (apply #'lurk-buttonify-urls strings) "\n")
492                        'face (lurk-get-context-facelist context)
493                        'read-only t
494                        'context context
495                        'invisible context-atom)))))))
496   (lurk-scroll-windows-to-last-line))
497
498 (defun lurk-display-message (from to text)
499   (let ((context (if (eq 'channel (lurk-get-context-type to))
500                      to
501                    (if (equal to lurk-nick) from to))))
502     (lurk-display-string
503      context
504      (propertize
505       (pcase (lurk-get-context-type to)
506         ('channel (concat to " <" from ">"))
507         ('nick (concat "[" from " -> " to "]"))
508         (_
509          (error "Unsupported context type")))
510       'face (lurk-get-context-facelist context))
511      text)))
512
513 (defun lurk-display-action (from to action-text)
514   (let ((context (if (eq 'channel (lurk-get-context-type to))
515                      to
516                    (if (equal to lurk-nick) from to))))
517     (lurk-display-string
518      context
519      (propertize
520       (concat context " * " from)
521       'face (lurk-get-context-facelist context))
522      action-text)))
523
524 (defun lurk-display-notice (context &rest notices)
525   (lurk-display-string
526    context
527    (propertize lurk-notice-prefix 'face 'lurk-notice)
528    (apply #'concat notices)))
529
530 (defun lurk-display-error (&rest messages)
531   (lurk-display-string
532    nil
533    (propertize lurk-error-prefix 'face 'lurk-error)
534    (apply #'concat messages)))
535
536 (defun lurk-highlight-context (context)
537   (maphash
538    (lambda (this-context facelist)
539      (if (equal this-context context)
540          (setcar facelist 'lurk-text)
541        (setcar facelist 'lurk-faded)))
542    lurk-context-facelists)
543   (force-window-update "*lurk*"))
544
545 (defun lurk-zoom-in (context)
546   (with-current-buffer "*lurk*"
547     (maphash
548      (lambda (this-context _)
549        (when this-context
550          (let ((this-context-atom (intern this-context)))
551            (if (equal this-context context)
552                (remove-from-invisibility-spec this-context-atom)
553              (add-to-invisibility-spec this-context-atom)))))
554      lurk-context-facelists)
555     (force-window-update "*lurk*"))
556   (lurk-scroll-windows-to-last-line))
557
558 (defun lurk-zoom-out ()
559   (with-current-buffer "*lurk*"
560     (maphash
561      (lambda (this-context _)
562        (let ((this-context-atom (if this-context (intern this-context) nil)))
563          (remove-from-invisibility-spec this-context-atom)))
564      lurk-context-facelists)
565     (force-window-update "*lurk*"))
566   (lurk-scroll-windows-to-last-line))
567
568 (defun lurk-clear-context (context)
569   (with-current-buffer "*lurk*"
570     (save-excursion
571       (goto-char (point-min))
572       (let ((inhibit-read-only t)
573             (match nil))
574         (while (setq match (text-property-search-forward 'context context t))
575           (delete-region (prop-match-beginning match)
576                          (prop-match-end match)))))))
577
578 (defconst lurk-url-regex
579   (rx (:
580        (group (+ alpha))
581        "://"
582        (group (or (+ (any alnum "." "-"))
583                   (+ (any alnum ":"))))
584        (opt (group (: ":" (+ digit))))
585        (opt (group (: "/"
586                       (opt
587                        (* (any alnum "-/.,#:%=&_?~@+"))
588                        (any alnum "-/#:%=&_~@+")))))))
589   "Imperfect regex used to find URLs in plain text.")
590
591 (defun lurk-click-url (button)
592   (browse-url (button-get button 'url)))
593
594 (defun lurk-buttonify-urls (&rest strings)
595   "Turn substrings which look like urls in STRING into clickable buttons."
596   (with-temp-buffer
597     (apply #'insert strings)
598     (goto-char (point-min))
599     (while (re-search-forward lurk-url-regex nil t)
600       (let ((url (match-string 0)))
601         (make-text-button (match-beginning 0)
602                           (match-end 0)
603                           'action #'lurk-click-url
604                           'url url
605                           'follow-link t
606                           'face 'button
607                           'help-echo "Open URL in browser.")))
608     (buffer-string)))
609
610 (defun lurk-add-formatting (string)
611   (with-temp-buffer
612     (insert string)
613     (goto-char (point-min))
614     (let ((bold nil)
615           (italics nil)
616           (underline nil)
617           (strikethrough nil)
618           (prev-point (point)))
619       (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
620                                         (: "\x03" (+ digit) (opt "," (* digit)))))
621                                 nil t)
622         (let ((beg (+ (match-beginning 0) 1)))
623           (if bold
624               (add-face-text-property prev-point beg '(:weight bold)))
625           (if italics
626               (add-face-text-property prev-point beg '(:slant italic)))
627           (if underline
628               (add-face-text-property prev-point beg '(:underline t)))
629           (if strikethrough
630               (add-face-text-property prev-point beg '(:strike-through t)))
631           (pcase (match-string 0)
632             ("\x02" (setq bold (not bold)))
633             ("\x1D" (setq italics (not italics)))
634             ("\x1F" (setq underline (not underline)))
635             ("\x1E" (setq strikethrough (not strikethrough)))
636             ("\x0F" ; Reset
637              (setq bold nil)
638              (setq italics nil)
639              (setq underline nil)
640              (setq strikethrough nil))
641             (_))
642           (delete-region (match-beginning 0) (match-end 0))
643           (setq prev-point (point)))))
644     (buffer-string)))
645
646
647 ;;; Message evaluation
648 ;;
649
650 (defun lurk-eval-msg-string (string)
651   (if lurk-debug
652       (lurk-display-string nil nil string))
653   (let* ((msg (lurk-string->msg string)))
654     (lurk-process-autoreplies msg)
655     (pcase (lurk-msg-cmd msg)
656       ("PING"
657        (lurk-send-msg
658         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
659
660       ("PONG")
661
662       ("001"
663        (let* ((params (lurk-msg-params msg))
664               (nick (elt params 0))
665               (text (string-join (seq-drop params 1) " ")))
666          (setq lurk-nick nick)
667          (lurk-display-notice nil text)))
668
669       ("353" ; NAMEREPLY
670        (let* ((params (lurk-msg-params msg))
671               (channel (elt params 2))
672               (names (split-string (elt params 3))))
673          (if (lurk-context-known-p channel)
674              (lurk-add-context-users channel names)
675            (lurk-display-notice nil "Users in " channel ": " (string-join names " ")))))
676
677       ("366" ; ENDOFNAMES
678        (let* ((params (lurk-msg-params msg))
679               (channel (elt params 1)))
680          (if (lurk-context-known-p channel)
681              (lurk-display-notice
682               channel
683               (lurk--as-string (length (lurk-get-context-users channel)))
684               " users in " channel)
685            (lurk-display-notice nil "End of " channel " names list."))))
686
687       ("331"
688        (let* ((params (lurk-msg-params msg))
689               (channel (elt params 1)))
690          (lurk-display-notice
691           channel
692           "No topic set.")))
693
694       ("332"
695        (let* ((params (lurk-msg-params msg))
696               (channel (elt params 1))
697               (topic (elt params 2)))
698          (lurk-display-notice channel "Topic: " topic)))
699
700       ("333") ; Avoid displaying these
701
702       ((rx (= 3 (any digit)))
703        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
704
705       ((and "JOIN"
706             (guard (equal lurk-nick (lurk-msg-src msg))))
707        (let ((channel (car (lurk-msg-params msg))))
708          (lurk-add-context channel)
709          (lurk-set-current-context channel)
710          (lurk-display-notice channel "Joining channel " channel)
711          (lurk-render-prompt)))
712
713       ("JOIN"
714        (let ((channel (car (lurk-msg-params msg)))
715              (nick (lurk-msg-src msg)))
716          (lurk-add-context-users channel (list nick))
717          (if lurk-show-joins
718              (lurk-display-notice channel nick " joined channel " channel))))
719
720       ((and "PART"
721             (guard (equal lurk-nick (lurk-msg-src msg))))
722        (let ((channel (car (lurk-msg-params msg))))
723          (lurk-display-notice channel "Left channel " channel)
724          (lurk-del-context channel)
725          (if (equal channel lurk-current-context)
726              (lurk-set-current-context (lurk-get-next-context)))
727          (lurk-render-prompt)))
728
729       ("PART"
730        (let ((channel (car (lurk-msg-params msg)))
731              (nick (lurk-msg-src msg)))
732          (lurk-del-context-user channel nick)
733          (if lurk-show-joins
734              (lurk-display-notice channel nick " left channel " channel))))
735
736       ((and "KICK")
737        (let ((kicker-nick (lurk-msg-src msg))
738              (channel (car (lurk-msg-params msg)))
739              (nick (cadr (lurk-msg-params msg)))
740              (reason (caddr (lurk-msg-params msg))))
741          (if (equal nick lurk-nick)
742              (progn
743                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
744                (lurk-del-context channel)
745                (if (equal channel lurk-current-context)
746                    (lurk-set-current-context (lurk-get-next-context)))
747                (lurk-render-prompt))
748            (lurk-del-context-user channel nick)
749            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
750
751       ("QUIT"
752        (let ((nick (lurk-msg-src msg))
753              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
754          (lurk-del-user nick)
755          (if lurk-show-joins
756              (lurk-display-notice nil nick " quit: " reason))))
757
758       ((and "NICK"
759             (guard (equal lurk-nick (lurk-msg-src msg))))
760        (setq lurk-nick (car (lurk-msg-params msg)))
761        (lurk-display-notice nil "Set nick to " lurk-nick))
762
763       ("NICK"
764        (let ((old-nick (lurk-msg-src msg))
765              (new-nick (car (lurk-msg-params msg))))
766          (lurk-display-notice nil old-nick " is now known as " new-nick)
767          (lurk-rename-user old-nick new-nick)))
768
769       ("NOTICE"
770        (let ((nick (lurk-msg-src msg))
771              (channel (car (lurk-msg-params msg)))
772              (text (cadr (lurk-msg-params msg))))
773          (pcase text
774            ((rx (: "\01VERSION "
775                    (let version (* (not "\01")))
776                    "\01"))
777             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
778            (_
779             (lurk-display-notice nil text)))))
780
781       ("PRIVMSG"
782        (let* ((from (lurk-msg-src msg))
783               (params (lurk-msg-params msg))
784               (to (car params))
785               (text (cadr params)))
786          (pcase text
787            ("\01VERSION\01"
788             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
789               (lurk-send-msg (lurk-msg nil nil "NOTICE"
790                                        (list from (concat "\01VERSION "
791                                                           version-string
792                                                           "\01")))))
793             (lurk-display-notice nil "CTCP version request received from " from))
794
795            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
796             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
797             (lurk-display-notice from "CTCP ping received from " from))
798
799            ("\01USERINFO\01"
800             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
801
802            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
803             (lurk-display-action from to action-text))
804
805            (_
806             (lurk-display-message from to text)))))
807       (_
808        (lurk-display-notice nil (lurk-msg->string msg))))))
809
810
811 ;;; User-defined responses
812
813
814 (defvar lurk-autoreply-table nil
815   "Table of autoreply messages.
816
817 Each autoreply is a list of two elements: (matcher reply)
818
819 Here matcher is a list:
820
821 (network src cmd params ...)
822
823 and reply is another list:
824
825  (cmd params ...)
826
827 Each entry in the matcher list is a regular expression tested against the
828 corresponding values in the incomming message.  Entries can be nil,
829 in which case they match anything.")
830
831 (defun lurk--lists-equal (l1 l2)
832     (if (and l1 l2)
833         (if (or (not (and (car l1) (car l2)))
834                 (string-match (car l1) (car l2)))
835             (lurk--lists-equal (cdr l1) (cdr l2))
836           nil)
837       t))
838
839 (defun lurk-process-autoreply (msg autoreply)
840   (let ((matcher (car autoreply))
841         (reply (cadr autoreply)))
842     (let ((network (car matcher)))
843       (when (and (or (not network)
844                      (and (get-process "lurk")
845                           (equal (car (process-contact (get-process "lurk")))
846                                  (cadr (assoc network lurk-networks)))))
847                  (lurk--lists-equal (cdr matcher)
848                                     (append (list (lurk-msg-src msg)
849                                                   (lurk-msg-cmd msg))
850                                             (lurk-msg-params msg))))
851         (lurk-send-msg
852          (lurk-msg nil nil (car reply) (cdr reply)))))))
853
854 (defun lurk-process-autoreplies (msg)
855   (mapc
856    (lambda (autoreply)
857      (lurk-process-autoreply msg autoreply))
858    lurk-autoreply-table))
859
860
861 ;;; Commands
862 ;;
863
864 (defvar lurk-command-table
865   '(("DEBUG" "Toggle debug mode on/off." lurk-command-debug lurk-boolean-completions)
866     ("HEADER" "Toggle display of header." lurk-command-header lurk-boolean-completions)
867     ("CONNECT" "Connect to an IRC network." lurk-command-connect lurk-network-completions)
868     ("NETWORKS" "List known IRC networks." lurk-command-networks)
869     ("JOIN" "Join one or more channels." lurk-command-join)
870     ("TOPIC" "Set topic for current channel." lurk-command-topic)
871     ("ME" "Display action." lurk-command-me)
872     ("VERSION" "Request version of another user's client via CTCP." lurk-command-version lurk-nick-completions)
873     ("PART" "Leave channel." lurk-command-part lurk-context-completions)
874     ("QUIT" "Disconnect from current network." lurk-command-quit)
875     ("NICK" "Change nick." lurk-command-nick)
876     ("LIST" "Display details of one or more channels." lurk-command-list)
877     ("WHOIS" "Ask server for details of nick." nil lurk-nick-completions)
878     ("MSG" "Send private message to user." lurk-command-msg lurk-nick-completions)
879     ("CLEAR" "Clear buffer text." lurk-command-clear lurk-context-completions)
880     ("HELP" "Display help on client commands." lurk-command-help lurk-help-completions))
881   "Table of commands explicitly supported by Lurk.")
882
883 (defun lurk-boolean-completions ()
884   '("on" "off"))
885
886 (defun lurk-network-completions ()
887   (mapcar (lambda (row) (car row)) lurk-networks))
888
889 (defun lurk-nick-completions ()
890   (lurk-get-context-users lurk-current-context))
891
892 (defun lurk-context-completions ()
893   (lurk-get-context-list))
894
895 (defun lurk-help-completions ()
896   (mapcar (lambda (row) (car row)) lurk-command-table))
897
898 (defun lurk-command-help (params)
899   (if params
900       (let* ((cmd-str (upcase (car params)))
901              (row (assoc cmd-str lurk-command-table #'equal)))
902         (if row
903             (progn
904               (lurk-display-notice nil "Help for \x02" cmd-str "\x02:")
905               (lurk-display-notice nil "  " (elt row 1)))
906           (lurk-display-notice nil "No such (client-interpreted) command.")))
907     (lurk-display-notice nil "Client-interpreted commands:")
908     (dolist (row lurk-command-table)
909       (lurk-display-notice nil "  \x02" (elt row 0) "\x02: " (elt row 1)))
910     (lurk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
911
912 (defun lurk-command-debug (params)
913   (setq lurk-debug 
914         (if params
915             (if (equal (upcase (car params)) "ON")
916                 t
917               nil)
918           (not lurk-debug)))
919   (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
920
921 (defun lurk-command-header (params)
922   (if
923       (if params
924           (equal (upcase (car params)) "ON")
925         (not header-line-format))
926       (progn
927         (lurk-setup-header)
928         (lurk-display-notice nil "Header enabled."))
929     (setq-local header-line-format nil)
930     (lurk-display-notice nil "Header disabled.")))
931
932 (defun lurk-command-connect (params)
933   (if params
934       (let ((network (car params)))
935         (lurk-display-notice nil "Attempting to connect to " network "...")
936         (lurk-connect network))
937     (lurk-display-notice nil "Usage: /connect <network>")))
938
939 (defun lurk-command-networks (params)
940   (lurk-display-notice nil "Currently-known networks:")
941   (dolist (row lurk-networks)
942     (seq-let (network server port &rest others) row
943       (lurk-display-notice nil "\t" network
944                            " [" server
945                            " " (number-to-string port) "]")))
946   (lurk-display-notice nil "(Modify the `lurk-networks' variable to add more.)"))
947
948 (defun lurk-command-join (params)
949   (if params
950       (dolist (channel params)
951         (lurk-send-msg (lurk-msg nil nil "JOIN" channel)))
952     (lurk-display-notice nil "Usage: /join channel [channel2 ...]")))
953
954 (defun lurk-command-part (params)
955   (let ((channel (if params (car params) lurk-current-context)))
956     (if channel
957         (lurk-send-msg (lurk-msg nil nil "PART" channel))
958       (lurk-display-error "No current channel to leave."))))
959
960 (defun lurk-command-version (params)
961   (if params
962       (let ((nick (car params)))
963         (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
964                                  (list nick "\01VERSION\01")))
965         (lurk-display-notice nil "CTCP version request sent to " nick))
966     (lurk-display-notice nil "Usage: /version <nick>")))
967
968 (defun lurk-command-quit (params)
969   (let ((quit-msg (if params (string-join params " ") lurk-default-quit-msg)))
970     (lurk-send-msg (lurk-msg nil nil "QUIT" quit-msg))))
971
972 (defun lurk-command-nick (params)
973   (let ((new-nick (if params (string-join params " ") nil)))
974     (if new-nick
975         (if (lurk-connected-p)
976             (lurk-send-msg (lurk-msg nil nil "NICK" new-nick))
977           (setq lurk-nick nick)
978           (lurk-display-notice nil "Set default nick to '" nick "'."))
979       (lurk-display-notice nil "Current nick: " lurk-nick))))
980
981 (defun lurk-command-me (params)
982   (if lurk-current-context
983       (if params
984           (let* ((action (string-join params " "))
985                  (ctcp-text (concat "\01ACTION " action "\01")))
986             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
987                                      (list lurk-current-context ctcp-text)))
988             (lurk-display-action lurk-nick lurk-current-context action))
989         (lurk-display-notice nil "Usage: /me <action>"))
990     (lurk-display-notice nil "No current channel.")))
991
992 (defun lurk-command-list (params)
993   (if (not params)
994       (lurk-display-notice nil "This command can generate lots of output. Use `/LIST -yes' if you really want this, or `/LIST <channel_regexp>' to reduce the output.")
995     (if (equal (upcase (car params)) "-YES")
996         (lurk-send-msg (lurk-msg nil nil "LIST"))
997       (lurk-send-msg (lurk-msg nil nil "LIST" (car params))))))
998
999 (defun lurk-command-topic (params)
1000   (if lurk-current-context
1001       (if params
1002           (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context (string-join params " ")))
1003         (lurk-display-notice nil "Usage: /topic <new topic>"))
1004     (lurk-display-notice nil "No current channel.")))
1005
1006 (defun lurk-command-msg (params)
1007   (if (and params (>= (length params) 2))
1008       (let ((to (car params))
1009             (text (string-join (cdr params) " ")))
1010         (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
1011         (lurk-display-message lurk-nick to text))
1012     (lurk-display-notice nil "Usage: /msg <nick> <message>")))
1013
1014 (defun lurk-command-clear (params)
1015   (if (not params)
1016       (lurk-clear-buffer)
1017     (dolist (context params)
1018       (lurk-clear-context context))))
1019
1020 ;;; Command entering
1021 ;;
1022
1023 (defun lurk-enter-string (string)
1024   (if (string-prefix-p "/" string)
1025       (pcase string
1026         ((rx (: "/" (let cmd-str (+ (not whitespace)))
1027                 (opt (+ whitespace)
1028                      (let params-str (+ anychar))
1029                      string-end)))
1030          (let ((command-row (assoc (upcase  cmd-str) lurk-command-table #'equal))
1031                (params (if params-str
1032                            (split-string params-str nil t)
1033                          nil)))
1034            (if (and command-row (elt command-row 2))
1035                (funcall (elt command-row 2) params)
1036              (lurk-send-msg (lurk-msg nil nil (upcase cmd-str) params)))))
1037         (_
1038          (lurk-display-error "Badly formed command.")))
1039     (unless (string-empty-p string)
1040       (if lurk-current-context
1041           (progn
1042             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
1043                                      lurk-current-context
1044                                      string))
1045             (lurk-display-message lurk-nick lurk-current-context string))
1046         (lurk-display-error "No current context.")))))
1047
1048
1049 ;;; Command history
1050 ;;
1051
1052 (defvar lurk-history nil
1053   "Commands and messages sent in current session.")
1054
1055 (defvar lurk-history-index nil)
1056
1057 (defun lurk-history-cycle (delta)
1058   (when lurk-history
1059     (with-current-buffer "*lurk*"
1060       (if lurk-history-index
1061           (setq lurk-history-index
1062                 (max 0
1063                      (min (- (length lurk-history) 1)
1064                           (+ delta lurk-history-index))))
1065         (setq lurk-history-index 0))
1066       (delete-region lurk-input-marker (point-max))
1067       (insert (elt lurk-history lurk-history-index)))))
1068
1069
1070 ;;; Interactive functions
1071 ;;
1072
1073 (defun lurk-cycle-contexts-forward ()
1074   (interactive)
1075   (lurk-cycle-contexts))
1076
1077 (defun lurk-cycle-contexts-reverse ()
1078   (interactive)
1079   (lurk-cycle-contexts t))
1080
1081 (defvar lurk-zoomed nil
1082   "Keeps track of zoom status.")
1083
1084 (defun lurk-toggle-zoom ()
1085   (interactive)
1086   (if lurk-zoomed
1087       (lurk-zoom-out)
1088     (lurk-zoom-in lurk-current-context))
1089   (setq lurk-zoomed (not lurk-zoomed)))
1090
1091 (defun lurk-history-next ()
1092   (interactive)
1093   (lurk-history-cycle -1))
1094
1095 (defun lurk-history-prev ()
1096   (interactive)
1097   (lurk-history-cycle +1))
1098
1099 (defun lurk-complete-input ()
1100   (interactive)
1101   (let ((completion-ignore-case t))
1102     (when (and (>= (point) lurk-input-marker))
1103       (pcase (buffer-substring lurk-input-marker (point))
1104         ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
1105          (let ((space-idx (save-excursion
1106                             (re-search-backward " " lurk-input-marker t)))
1107                (table-row (assoc (upcase cmd-str) lurk-command-table #'equal)))
1108            (if (and table-row (elt table-row 3))
1109                (let* ((completions-nospace (funcall (elt table-row 3)))
1110                       (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
1111                  (completion-in-region (+ 1 space-idx) (point) completions)))))
1112         ((rx (: "/" (* (not whitespace)) string-end))
1113          (message (buffer-substring lurk-input-marker (point)))
1114          (completion-in-region lurk-input-marker (point)
1115                                (mapcar (lambda (row) (concat "/" (car row) " "))
1116                                        lurk-command-table)))
1117         (_
1118          (let* ((end (max lurk-input-marker (point)))
1119                 (space-idx (save-excursion
1120                              (re-search-backward " " lurk-input-marker t)))
1121                 (start (if space-idx (+ 1 space-idx) lurk-input-marker)))
1122            (unless (string-prefix-p "/" (buffer-substring start end))
1123              (completion-in-region start end (lurk-get-context-users lurk-current-context)))))))))
1124
1125 (defun lurk-enter ()
1126   "Enter current contents of line after prompt."
1127   (interactive)
1128   (with-current-buffer "*lurk*"
1129     (let ((line (buffer-substring lurk-input-marker (point-max))))
1130       (push line lurk-history)
1131       (setq lurk-history-index nil)
1132       (let ((inhibit-read-only t))
1133         (delete-region lurk-input-marker (point-max)))
1134       (lurk-enter-string line))))
1135
1136
1137 ;;; Mode
1138 ;;
1139
1140 (defvar lurk-mode-map
1141   (let ((map (make-sparse-keymap)))
1142     (define-key map (kbd "RET") 'lurk-enter)
1143     (define-key map (kbd "TAB") 'lurk-complete-input)
1144     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
1145     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
1146     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
1147     (define-key map (kbd "<C-up>") 'lurk-history-prev)
1148     (define-key map (kbd "<C-down>") 'lurk-history-next)
1149     (when (fboundp 'evil-define-key*)
1150       (evil-define-key* 'motion map
1151         (kbd "TAB") 'lurk-complete-input))
1152     map))
1153
1154 (defvar lurk-mode-map)
1155
1156 (define-derived-mode lurk-mode text-mode "lurk"
1157   "Major mode for LURK.")
1158
1159 (when (fboundp 'evil-set-initial-state)
1160   (evil-set-initial-state 'lurk-mode 'insert))
1161
1162
1163 ;;; Main start procedure
1164 ;;
1165
1166 (defun lurk (&optional network)
1167   "Start lurk or just switch to the lurk buffer if one already exists.
1168 Also connect to NETWORK if non-nil."
1169   (interactive)
1170   (if (get-buffer "*lurk*")
1171       (switch-to-buffer "*lurk*")
1172     (switch-to-buffer "*lurk*")
1173     (lurk-mode)
1174     (lurk-setup-buffer)
1175     (if network
1176         (lurk-command-connect (list network))))
1177   "Started LURK.")
1178
1179
1180 ;;; lurk.el ends here