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