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