Fixed bug where /names causes heaps of channels to be added.
[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
413 ;;; Output formatting and highlighting
414 ;;
415
416 ;; Idea: the face text property can be a list of faces, applied in
417 ;; order.  By assigning each context a unique list and keeping track
418 ;; of these in a hash table, we can easily switch the face
419 ;; corresponding to a particular context by modifying the elements of
420 ;; this list.
421 ;;
422 ;; More subtly, we make only the cdrs of this list shared among
423 ;; all text of a given context, allowing the cars to be different
424 ;; and for different elements of the context-specific text to have
425 ;; different styling.
426
427 ;; Additionally, we allow selective hiding of contexts via
428 ;; the buffer-invisibility-spec.
429
430 (defvar lurk-context-facelists (make-hash-table :test 'equal)
431   "List of seen contexts and associated face lists.")
432
433 (defun lurk-get-context-facelist (context)
434   (let ((facelist (gethash context lurk-context-facelists)))
435     (unless facelist
436       (setq facelist (list 'lurk-text))
437       (puthash context facelist lurk-context-facelists))
438     facelist))
439
440 (defun lurk--fill-strings (col indent &rest strings)
441   (with-temp-buffer
442     (setq buffer-invisibility-spec nil)
443     (let ((fill-column col)
444           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
445       (apply #'insert strings)
446       (fill-region (point-min) (point-max) nil t)
447       (buffer-string))))
448
449 (defun lurk-display-string (context prefix &rest strings)
450   (with-current-buffer (get-buffer-create "*lurk*")
451     (save-excursion
452       (goto-char lurk-prompt-marker)
453       (let* ((inhibit-read-only t)
454              (old-pos (marker-position lurk-prompt-marker))
455              (padded-timestamp (concat (format-time-string "%H:%M ")))
456              (padded-prefix (if prefix (concat prefix " ") ""))
457              (context-atom (if context (intern context) nil)))
458         (insert-before-markers
459          (lurk--fill-strings
460           80
461           (+ (length padded-timestamp)
462              (length padded-prefix))
463           (propertize padded-timestamp
464                       'face 'lurk-timestamp
465                       'read-only t
466                       'context context
467                       'invisible context-atom)
468           (propertize padded-prefix
469                       'read-only t
470                       'context context
471                       'invisible context-atom)
472           (lurk-add-formatting
473            (propertize (concat (apply #'lurk-buttonify-urls strings) "\n")
474                        'face (lurk-get-context-facelist context)
475                        'read-only t
476                        'context context
477                        'invisible context-atom))))))))
478
479 (defun lurk-display-message (from to text)
480   (let ((context (if (eq 'channel (lurk-get-context-type to))
481                      to
482                    (if (equal to lurk-nick) from to))))
483     (lurk-display-string
484      context
485      (propertize
486       (pcase (lurk-get-context-type to)
487         ('channel (concat to " <" from ">"))
488         ('nick (concat "[" from " -> " to "]"))
489         (_
490          (error "Unsupported context type")))
491       'face (lurk-get-context-facelist context))
492      text)))
493
494 (defun lurk-display-action (from to action-text)
495   (let ((context (if (eq 'channel (lurk-get-context-type to))
496                      to
497                    (if (equal to lurk-nick) from to))))
498     (lurk-display-string
499      context
500      (propertize
501       (concat context " * " from)
502       'face (lurk-get-context-facelist context))
503      action-text)))
504
505 (defun lurk-display-notice (context &rest notices)
506   (lurk-display-string
507    context
508    (propertize lurk-notice-prefix 'face 'lurk-notice)
509    (apply #'concat notices)))
510
511 (defun lurk-display-error (&rest messages)
512   (lurk-display-string
513    nil
514    (propertize lurk-error-prefix 'face 'lurk-error)
515    (apply #'concat messages)))
516
517 (defun lurk-highlight-context (context)
518   (maphash
519    (lambda (this-context facelist)
520      (if (equal this-context context)
521          (setcar facelist 'lurk-text)
522        (setcar facelist 'lurk-faded)))
523    lurk-context-facelists)
524   (force-window-update "*lurk*"))
525
526 (defun lurk-zoom-in (context)
527   (with-current-buffer "*lurk*"
528     (maphash
529      (lambda (this-context _)
530        (when this-context
531          (let ((this-context-atom (intern this-context)))
532            (if (equal this-context context)
533                (remove-from-invisibility-spec this-context-atom)
534              (add-to-invisibility-spec this-context-atom)))))
535      lurk-context-facelists)
536     (force-window-update "*lurk*")))
537
538 (defun lurk-zoom-out ()
539   (with-current-buffer "*lurk*"
540     (maphash
541      (lambda (this-context _)
542        (let ((this-context-atom (if this-context (intern this-context) nil)))
543          (remove-from-invisibility-spec this-context-atom)))
544      lurk-context-facelists)
545     (force-window-update "*lurk*")))
546
547 (defconst lurk-url-regex
548   (rx (:
549        (group (+ alpha))
550        "://"
551        (group (or (+ (any alnum "." "-"))
552                   (+ (any alnum ":"))))
553        (opt (group (: ":" (+ digit))))
554        (opt (group (: "/"
555                       (opt
556                        (* (any alnum "-/.,#:%=&_?~@+"))
557                        (any alnum "-/#:%=&_~@+")))))))
558   "Imperfect regex used to find URLs in plain text.")
559
560 (defun lurk-click-url (button)
561   (browse-url (button-get button 'url)))
562
563 (defun lurk-buttonify-urls (&rest strings)
564   "Turn substrings which look like urls in STRING into clickable buttons."
565   (with-temp-buffer
566     (apply #'insert strings)
567     (goto-char (point-min))
568     (while (re-search-forward lurk-url-regex nil t)
569       (let ((url (match-string 0)))
570         (make-text-button (match-beginning 0)
571                           (match-end 0)
572                           'action #'lurk-click-url
573                           'url url
574                           'follow-link t
575                           'face 'button
576                           'help-echo "Open URL in browser.")))
577     (buffer-string)))
578
579 (defun lurk-add-formatting (string)
580   (with-temp-buffer
581     (insert string)
582     (goto-char (point-min))
583     (let ((bold nil)
584           (italics nil)
585           (underline nil)
586           (strikethrough nil)
587           (prev-point (point)))
588       (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
589                                         (: "\x03" (+ digit) (opt "," (* digit))))) nil t)
590         (let ((beg (+ (match-beginning 0) 1)))
591           (if bold
592               (add-face-text-property prev-point beg '(:weight bold)))
593           (if italics
594               (add-face-text-property prev-point beg '(:slant italic)))
595           (if underline
596               (add-face-text-property prev-point beg '(:underline t)))
597           (if strikethrough
598               (add-face-text-property prev-point beg '(:strike-through t)))
599           (pcase (match-string 0)
600             ("\x02" (setq bold (not bold)))
601             ("\x1D" (setq italics (not italics)))
602             ("\x1F" (setq underline (not underline)))
603             ("\x1E" (setq strikethrough (not strikethrough)))
604             ("\x0F" ; Reset
605              (setq bold nil)
606              (setq italics nil)
607              (setq underline nil)
608              (setq strikethrough nil))
609             (_))
610           (delete-region (match-beginning 0) (match-end 0))
611           (setq prev-point (point)))))
612     (buffer-string)))
613
614
615 ;;; Message evaluation
616 ;;
617
618 (defun lurk-eval-msg-string (string)
619   (if lurk-debug
620       (lurk-display-string nil nil string))
621   (let* ((msg (lurk-string->msg string)))
622     (lurk-process-autoreplies msg)
623     (pcase (lurk-msg-cmd msg)
624       ("PING"
625        (lurk-send-msg
626         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
627
628       ("PONG")
629
630       ("001"
631        (let* ((params (lurk-msg-params msg))
632               (nick (elt params 0))
633               (text (string-join (seq-drop params 1) " ")))
634          (setq lurk-nick nick)
635          (lurk-display-notice nil text)))
636
637       ("353" ; NAMEREPLY
638        (let* ((params (lurk-msg-params msg))
639               (channel (elt params 2))
640               (names (split-string (elt params 3))))
641          (if (lurk-context-known-p channel)
642              (lurk-add-context-users channel names)
643            (lurk-display-notice nil "Users in " channel ": " (string-join names " ")))))
644
645       ("366" ; ENDOFNAMES
646        (let* ((params (lurk-msg-params msg))
647               (channel (elt params 1)))
648          (if (lurk-context-known-p channel)
649              (lurk-display-notice
650               channel
651               (lurk--as-string (length (lurk-get-context-users channel)))
652               " users in " channel)
653            (lurk-display-notice nil "End of " channel " names list."))))
654
655       ("331"
656        (let* ((params (lurk-msg-params msg))
657               (channel (elt params 1)))
658          (lurk-display-notice
659           channel
660           "No topic set.")))
661
662       ("332"
663        (let* ((params (lurk-msg-params msg))
664               (channel (elt params 1))
665               (topic (elt params 2)))
666          (lurk-display-notice channel "Topic: " topic)))
667
668       ("333") ; Avoid displaying these
669
670       ((rx (= 3 (any digit)))
671        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
672
673       ((and "JOIN"
674             (guard (equal lurk-nick (lurk-msg-src msg))))
675        (let ((channel (car (lurk-msg-params msg))))
676          (lurk-add-context channel)
677          (lurk-set-current-context channel)
678          (lurk-display-notice channel "Joining channel " channel)
679          (lurk-render-prompt)))
680
681       ("JOIN"
682        (let ((channel (car (lurk-msg-params msg)))
683              (nick (lurk-msg-src msg)))
684          (lurk-add-context-users channel (list nick))
685          (if lurk-show-joins
686              (lurk-display-notice channel nick " joined channel " channel))))
687
688       ((and "PART"
689             (guard (equal lurk-nick (lurk-msg-src msg))))
690        (let ((channel (car (lurk-msg-params msg))))
691          (lurk-display-notice channel "Left channel " channel)
692          (lurk-del-context channel)
693          (if (equal channel lurk-current-context)
694              (lurk-set-current-context (lurk-get-next-context)))
695          (lurk-render-prompt)))
696
697       ("PART"
698        (let ((channel (car (lurk-msg-params msg)))
699              (nick (lurk-msg-src msg)))
700          (lurk-del-context-user channel nick)
701          (if lurk-show-joins
702              (lurk-display-notice channel nick " left channel " channel))))
703
704       ((and "KICK")
705        (let ((kicker-nick (lurk-msg-src msg))
706              (channel (car (lurk-msg-params msg)))
707              (nick (cadr (lurk-msg-params msg)))
708              (reason (caddr (lurk-msg-params msg))))
709          (if (equal nick lurk-nick)
710              (progn
711                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
712                (lurk-del-context channel)
713                (if (equal channel lurk-current-context)
714                    (lurk-set-current-context (lurk-get-next-context)))
715                (lurk-render-prompt))
716            (lurk-del-context-user channel nick)
717            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
718
719       ("QUIT"
720        (let ((nick (lurk-msg-src msg))
721              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
722          (lurk-del-user nick)
723          (if lurk-show-joins
724              (lurk-display-notice nil nick " quit: " reason))))
725
726       ((and "NICK"
727             (guard (equal lurk-nick (lurk-msg-src msg))))
728        (setq lurk-nick (car (lurk-msg-params msg)))
729        (lurk-display-notice nil "Set nick to " lurk-nick))
730
731       ("NICK"
732        (let ((old-nick (lurk-msg-src msg))
733              (new-nick (car (lurk-msg-params msg))))
734          (lurk-display-notice nil old-nick " is now known as " new-nick)
735          (lurk-rename-user old-nick new-nick)))
736
737       ("NOTICE"
738        (let ((nick (lurk-msg-src msg))
739              (channel (car (lurk-msg-params msg)))
740              (text (cadr (lurk-msg-params msg))))
741          (pcase text
742            ((rx (: "\01VERSION "
743                    (let version (* (not "\01")))
744                    "\01"))
745             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
746            (_
747             (lurk-display-notice nil text)))))
748
749       ("PRIVMSG"
750        (let* ((from (lurk-msg-src msg))
751               (params (lurk-msg-params msg))
752               (to (car params))
753               (text (cadr params)))
754          (pcase text
755            ("\01VERSION\01"
756             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
757               (lurk-send-msg (lurk-msg nil nil "NOTICE"
758                                        (list from (concat "\01VERSION "
759                                                           version-string
760                                                           "\01")))))
761             (lurk-display-notice nil "CTCP version request received from " from))
762
763            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
764             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
765             (lurk-display-notice from "CTCP ping received from " from))
766
767            ("\01USERINFO\01"
768             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
769
770            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
771             (lurk-display-action from to action-text))
772
773            (_
774             (lurk-display-message from to text)))))
775       (_
776        (lurk-display-notice nil (lurk-msg->string msg))))))
777
778
779 ;;; User-defined responses
780
781
782 (defvar lurk-autoreply-table nil
783   "Table of autoreply messages.
784
785 Each autoreply is a list of two elements: (matcher reply)
786
787 Here matcher is a list:
788
789 (network src cmd params ...)
790
791 and reply is another list:
792
793  (cmd params ...)
794
795 Each entry in the matcher list is a regular expression tested against the
796 corresponding values in the incomming message.  Entries can be nil,
797 in which case they match anything.")
798
799 (defun lurk--lists-equal (l1 l2)
800     (if (and l1 l2)
801         (if (or (not (and (car l1) (car l2)))
802                 (string-match (car l1) (car l2)))
803             (lurk--lists-equal (cdr l1) (cdr l2))
804           nil)
805       t))
806
807 (defun lurk-process-autoreply (msg autoreply)
808   (let ((matcher (car autoreply))
809         (reply (cadr autoreply)))
810     (let ((network (car matcher)))
811       (when (and (or (not network)
812                      (and (get-process "lurk")
813                           (equal (car (process-contact (get-process "lurk")))
814                                  (cadr (assoc network lurk-networks)))))
815                  (lurk--lists-equal (cdr matcher)
816                                     (append (list (lurk-msg-src msg)
817                                                   (lurk-msg-cmd msg))
818                                             (lurk-msg-params msg))))
819         (lurk-send-msg
820          (lurk-msg nil nil (car reply) (cdr reply)))))))
821
822 (defun lurk-process-autoreplies (msg)
823   (mapc
824    (lambda (autoreply)
825      (lurk-process-autoreply msg autoreply))
826    lurk-autoreply-table))
827
828
829 ;;; Commands
830 ;;
831
832 (defvar lurk-command-table
833   '(("DEBUG" "Toggle debug mode on/off." lurk-command-debug lurk-boolean-completions)
834     ("HEADER" "Toggle display of header." lurk-command-header lurk-boolean-completions)
835     ("CONNECT" "Connect to an IRC network." lurk-command-connect lurk-network-completions)
836     ("NETWORKS" "List known IRC networks." lurk-command-networks)
837     ("TOPIC" "Set topic for current channel." lurk-command-topic)
838     ("ME" "Display action." lurk-command-me)
839     ("VERSION" "Request version of another user's client via CTCP." lurk-command-version)
840     ("PART" "Leave channel." lurk-command-part lurk-context-completions)
841     ("QUIT" "Disconnect from current network." lurk-command-quit)
842     ("NICK" "Change nick." lurk-command-nick)
843     ("LIST" "Display details of one or more channels." lurk-command-list)
844     ("MSG" "Send private message to user." lurk-command-msg lurk-nick-completions)
845     ("HELP" "Display help on client commands." lurk-command-help lurk-help-completions))
846   "Table of commands explicitly supported by Lurk.")
847
848 (defun lurk-boolean-completions ()
849   '("on" "off"))
850
851 (defun lurk-network-completions ()
852   (mapcar (lambda (row) (car row)) lurk-networks))
853
854 (defun lurk-nick-completions ()
855   (lurk-get-context-users lurk-current-context))
856
857 (defun lurk-context-completions ()
858   (lurk-get-context-list))
859
860 (defun lurk-help-completions ()
861   (mapcar (lambda (row) (car row)) lurk-command-table))
862
863 (defun lurk-command-help (params)
864   (if params
865       (let* ((cmd-str (upcase (car params)))
866              (row (assoc cmd-str lurk-command-table #'equal)))
867         (if row
868             (progn
869               (lurk-display-notice nil "Help for \x02" cmd-str "\x02:")
870               (lurk-display-notice nil "  " (elt row 1)))
871           (lurk-display-notice nil "No such (client-interpreted) command.")))
872     (lurk-display-notice nil "Client-interpreted commands:")
873     (dolist (row lurk-command-table)
874       (lurk-display-notice nil "  \x02" (elt row 0) "\x02: " (elt row 1)))
875     (lurk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
876
877 (defun lurk-command-debug (params)
878   (setq lurk-debug 
879         (if params
880             (if (equal (upcase (car params)) "ON")
881                 t
882               nil)
883           (not lurk-debug)))
884   (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
885
886 (defun lurk-command-header (params)
887   (if
888       (if params
889           (equal (upcase (car params)) "ON")
890         (not header-line-format))
891       (progn
892         (lurk-setup-header)
893         (lurk-display-notice nil "Header enabled."))
894     (setq-local header-line-format nil)
895     (lurk-display-notice nil "Header disabled.")))
896
897 (defun lurk-command-connect (params)
898   (if params
899       (let ((network (car params)))
900         (lurk-display-notice nil "Attempting to connect to " network "...")
901         (lurk-connect network))
902     (lurk-display-notice nil "Usage: /connect <network>")))
903
904 (defun lurk-command-networks (params)
905   (lurk-display-notice nil "Currently-known networks:")
906   (dolist (row lurk-networks)
907     (seq-let (network server port &rest others) row
908       (lurk-display-notice nil "\t" network
909                            " [" server
910                            " " (number-to-string port) "]")))
911   (lurk-display-notice nil "(Modify the `lurk-networks' variable to add more.)"))
912
913 (defun lurk-command-part (params)
914   (let ((channel (if params (car params) lurk-current-context)))
915     (if channel
916         (lurk-send-msg (lurk-msg nil nil "PART" channel))
917       (lurk-display-error "No current channel to leave."))))
918
919 (defun lurk-command-version (params)
920   (if params
921       (let ((nick (car params)))
922         (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
923                                  (list nick "\01VERSION\01")))
924         (lurk-display-notice nil "CTCP version request sent to " nick))
925     (lurk-display-notice nil "Usage: /version <nick>")))
926
927 (defun lurk-command-quit (params)
928   (let ((quit-msg (if params (string-join params " ") lurk-default-quit-msg)))
929     (lurk-send-msg (lurk-msg nil nil "QUIT" quit-msg))))
930
931 (defun lurk-command-nick (params)
932   (let ((new-nick (if params (string-join params " ") nil)))
933     (if new-nick
934         (if (lurk-connected-p)
935             (lurk-send-msg (lurk-msg nil nil "NICK" new-nick))
936           (setq lurk-nick nick)
937           (lurk-display-notice nil "Set default nick to '" nick "'."))
938       (lurk-display-notice nil "Current nick: " lurk-nick))))
939
940 (defun lurk-command-me (params)
941   (if lurk-current-context
942       (if params
943           (let* ((action (string-join params " "))
944                  (ctcp-text (concat "\01ACTION " action "\01")))
945             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
946                                      (list lurk-current-context ctcp-text)))
947             (lurk-display-action lurk-nick lurk-current-context action))
948         (lurk-display-notice nil "Usage: /me <action>"))
949     (lurk-display-notice nil "No current channel.")))
950
951 (defun lurk-command-list (params)
952   (if (not params)
953       (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.")
954     (if (equal (upcase (car params)) "-YES")
955         (lurk-send-msg (lurk-msg nil nil "LIST"))
956       (lurk-send-msg (lurk-msg nil nil "LIST" (car params))))))
957
958 (defun lurk-command-topic (params)
959   (if lurk-current-context
960       (if params
961           (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context (string-join params " ")))
962         (lurk-display-notice nil "Usage: /topic <new topic>"))
963     (lurk-display-notice nil "No current channel.")))
964
965 (defun lurk-command-msg (params)
966   (if (and params (>= (length params) 2))
967       (let ((to (car params))
968             (text (string-join (cdr params) " ")))
969         (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
970         (lurk-display-message lurk-nick to text))
971     (lurk-display-notice nil "Usage: /msg <nick> <message>")))
972
973
974 ;;; Command entering
975 ;;
976
977 (defun lurk-enter-string (string)
978   (if (string-prefix-p "/" string)
979       (pcase string
980         ((rx (: "/" (let cmd-str (+ (not whitespace)))
981                 (opt (+ whitespace)
982                      (let params-str (+ anychar))
983                      string-end)))
984          (let ((command-row (assoc (upcase  cmd-str) lurk-command-table #'equal))
985                (params (if params-str
986                            (split-string params-str nil t)
987                          nil)))
988            (if command-row
989                (funcall (elt command-row 2) params)
990              (lurk-send-msg (lurk-msg nil nil (upcase cmd-str) params)))))
991         (_
992          (lurk-display-error "Badly formed command.")))
993     (unless (string-empty-p string)
994       (if lurk-current-context
995           (progn
996             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
997                                      lurk-current-context
998                                      string))
999             (lurk-display-message lurk-nick lurk-current-context string))
1000         (lurk-display-error "No current context.")))))
1001
1002
1003 ;;; Command history
1004 ;;
1005
1006 (defvar lurk-history nil
1007   "Commands and messages sent in current session.")
1008
1009 (defvar lurk-history-index nil)
1010
1011 (defun lurk-history-cycle (delta)
1012   (when lurk-history
1013     (with-current-buffer "*lurk*"
1014       (if lurk-history-index
1015           (setq lurk-history-index
1016                 (max 0
1017                      (min (- (length lurk-history) 1)
1018                           (+ delta lurk-history-index))))
1019         (setq lurk-history-index 0))
1020       (delete-region lurk-input-marker (point-max))
1021       (insert (elt lurk-history lurk-history-index)))))
1022
1023
1024 ;;; Interactive functions
1025 ;;
1026
1027 (defun lurk-cycle-contexts-forward ()
1028   (interactive)
1029   (lurk-cycle-contexts))
1030
1031 (defun lurk-cycle-contexts-reverse ()
1032   (interactive)
1033   (lurk-cycle-contexts t))
1034
1035 (defvar lurk-zoomed nil
1036   "Keeps track of zoom status.")
1037
1038 (defun lurk-toggle-zoom ()
1039   (interactive)
1040   (if lurk-zoomed
1041       (lurk-zoom-out)
1042     (lurk-zoom-in lurk-current-context))
1043   (setq lurk-zoomed (not lurk-zoomed)))
1044
1045 (defun lurk-history-next ()
1046   (interactive)
1047   (lurk-history-cycle -1))
1048
1049 (defun lurk-history-prev ()
1050   (interactive)
1051   (lurk-history-cycle +1))
1052
1053 (defun lurk-complete-input ()
1054   (interactive)
1055   (let ((completion-ignore-case t))
1056     (when (and (>= (point) lurk-input-marker))
1057       (pcase (buffer-substring lurk-input-marker (point))
1058         ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
1059          (let ((space-idx (save-excursion
1060                             (re-search-backward " " lurk-input-marker t)))
1061                (table-row (assoc (upcase cmd-str) lurk-command-table #'equal)))
1062            (if (and table-row (elt table-row 3))
1063                (let* ((completions-nospace (funcall (elt table-row 3)))
1064                       (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
1065                  (completion-in-region (+ 1 space-idx) (point) completions)))))
1066         ((rx (: "/" (* (not whitespace)) string-end))
1067          (message (buffer-substring lurk-input-marker (point)))
1068          (completion-in-region lurk-input-marker (point)
1069                                (mapcar (lambda (row) (concat "/" (car row) " "))
1070                                        lurk-command-table)))
1071         (_
1072          (let* ((end (max lurk-input-marker (point)))
1073                 (space-idx (save-excursion
1074                              (re-search-backward " " lurk-input-marker t)))
1075                 (start (if space-idx (+ 1 space-idx) lurk-input-marker)))
1076            (unless (string-prefix-p "/" (buffer-substring start end))
1077              (completion-in-region start end (lurk-get-context-users lurk-current-context)))))))))
1078
1079 (defun lurk-enter ()
1080   "Enter current contents of line after prompt."
1081   (interactive)
1082   (with-current-buffer "*lurk*"
1083     (let ((line (buffer-substring lurk-input-marker (point-max))))
1084       (push line lurk-history)
1085       (setq lurk-history-index nil)
1086       (let ((inhibit-read-only t))
1087         (delete-region lurk-input-marker (point-max)))
1088       (lurk-enter-string line))))
1089
1090
1091 ;;; Mode
1092 ;;
1093
1094 (defvar lurk-mode-map
1095   (let ((map (make-sparse-keymap)))
1096     (define-key map (kbd "RET") 'lurk-enter)
1097     (define-key map (kbd "TAB") 'lurk-complete-input)
1098     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
1099     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
1100     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
1101     (define-key map (kbd "<C-up>") 'lurk-history-prev)
1102     (define-key map (kbd "<C-down>") 'lurk-history-next)
1103     (when (fboundp 'evil-define-key*)
1104       (evil-define-key* 'motion map
1105         (kbd "TAB") 'lurk-complete-input))
1106     map))
1107
1108 (defvar lurk-mode-map)
1109
1110 (define-derived-mode lurk-mode text-mode "lurk"
1111   "Major mode for LURK.")
1112
1113 (when (fboundp 'evil-set-initial-state)
1114   (evil-set-initial-state 'lurk-mode 'insert))
1115
1116
1117 ;;; Main start procedure
1118 ;;
1119
1120 (defun lurk (&optional network)
1121   "Start lurk or just switch to the lurk buffer if one already exists.
1122 Also connect to NETWORK if non-nil."
1123   (interactive)
1124   (if (get-buffer "*lurk*")
1125       (switch-to-buffer "*lurk*")
1126     (switch-to-buffer "*lurk*")
1127     (lurk-mode)
1128     (lurk-setup-buffer)
1129     (if network
1130         (lurk-command-connect (list network))))
1131   "Started LURK.")
1132
1133
1134 ;;; lurk.el ends here