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