Added user-defined responses.
[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     ("freenode" "chat.freenode.net" 6697)
50     ("tilde" "tilde.chat" 6697)
51     ("mbr" "mbrserver.com" 6667 :notls)
52     ("local" "localhost" 6697))
53   "IRC networks.")
54
55 (defcustom lurk-allow-ipv6 nil
56   "Set to non-nil to allow use of IPv6.")
57
58 (defcustom lurk-show-joins nil
59   "Set to non-nil to be notified of joins, parts and quits.")
60
61 (defcustom lurk-display-header t
62   "If non-nil, use buffer header to display information on current host and channel.")
63
64 ;;; Faces
65 ;;
66
67 (defface lurk-text
68   '((t :inherit default))
69   "Face used for Lurk text.")
70
71 (defface lurk-prompt
72   '((t :inherit org-priority))
73   "Face used for the prompt.")
74
75 (defface lurk-context
76   '((t :inherit org-tag))
77   "Face used for the context name in the prompt.")
78
79 (defface lurk-faded
80   '((t :inherit org-agenda-dimmed-todo-face))
81   "Face used for faded Lurk text.")
82
83 (defface lurk-timestamp
84   '((t :inherit org-agenda-dimmed-todo-face))
85   "Face used for timestamps.")
86
87 (defface lurk-error
88   '((t :inherit font-lock-regexp-grouping-construct))
89   "Face used for Lurk error text.")
90
91 (defface lurk-notice
92   '((t :inherit org-upcoming-deadline))
93   "Face used for Lurk notice text.")
94
95 ;;; Global variables
96 ;;
97
98 (defvar lurk-version "Lurk v0.1"
99   "Value of this string is used in response to CTCP version queries.")
100
101 (defvar lurk-notice-prefix "-!-")
102
103 (defvar lurk-error-prefix "!!!")
104
105 (defvar lurk-prompt-string ">")
106
107 (defvar lurk-debug nil
108   "If non-nil, enable debug mode.")
109
110
111 ;;; Utility procedures
112 ;;
113
114 (defun lurk--filtered-join (&rest args)
115   (string-join (seq-filter (lambda (el) el) args) " "))
116
117 (defun lurk--as-string (obj)
118   (if obj
119       (with-output-to-string (princ obj))
120     nil))
121
122
123 ;;; Network process
124 ;;
125
126 (defvar lurk-response "")
127
128 (defun lurk-filter (proc string)
129   (dolist (line (split-string (concat lurk-response string) "\n"))
130     (if (string-suffix-p "\r" line)
131         (lurk-eval-msg-string (string-trim line))
132       (setq lurk-response line))))
133
134 (defun lurk-sentinel (proc string)
135   (unless (equal "open" (string-trim string))
136     (lurk-display-error "Disconnected from server.")
137     (clrhash lurk-contexts)
138     (lurk-set-current-context nil)
139     (lurk-render-prompt)
140     (cancel-timer lurk-ping-timer)))
141
142 (defun lurk-start-process (network)
143   (let* ((row (assoc network lurk-networks))
144          (host (elt row 1))
145          (port (elt row 2))
146          (flags (seq-drop row 3)))
147     (make-network-process :name "lurk"
148                           :host host
149                           :service port
150                           :family (if lurk-allow-ipv6 nil 'ipv4)
151                           :filter #'lurk-filter
152                           :sentinel #'lurk-sentinel
153                           :nowait nil
154                           :tls-parameters (if (memq :notls flags)
155                                               nil
156                                             (cons 'gnutls-x509pki
157                                                   (gnutls-boot-parameters
158                                                    :type 'gnutls-x509pki
159                                                    :hostname host)))
160                           :buffer "*lurk*")))
161
162 (defvar lurk-ping-timer nil)
163 (defvar lurk-ping-period 60)
164
165 (defun lurk-ping-function ()
166   (lurk-send-msg (lurk-msg nil nil "PING" (car (process-contact (get-process "lurk")))))
167   (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))
168
169 (defun lurk-connect (network)
170   (if (get-process "lurk")
171       (lurk-display-error "Already connected.  Disconnect first.")
172     (if (not (assoc network lurk-networks))
173         (lurk-display-error "Network '" network "' is unknown.")
174       (clrhash lurk-contexts)
175       (lurk-set-current-context nil)
176       (lurk-start-process network)
177       (lurk-send-msg (lurk-msg nil nil "USER" lurk-nick 0 "*" lurk-nick))
178       (lurk-send-msg (lurk-msg nil nil "NICK" lurk-nick))
179       (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))))
180
181 (defun lurk-connected-p ()
182   (let ((proc (get-process "lurk")))
183     (and proc (eq (process-status proc) 'open))))
184
185 (defun lurk-send-msg (msg)
186   (if lurk-debug
187       (lurk-display-string nil nil (lurk-msg->string msg)))
188   (let ((proc (get-process "lurk")))
189     (if (and proc (eq (process-status proc) 'open))
190         (process-send-string proc (concat (lurk-msg->string msg) "\r\n"))
191       (lurk-display-error "No server connection established.")
192       (error "No server connection established"))))
193
194
195 ;;; Server messages
196 ;;
197
198 (defun lurk-msg (tags src cmd &rest params)
199   (list (lurk--as-string tags)
200         (lurk--as-string src)
201         (upcase (lurk--as-string cmd))
202         (mapcar #'lurk--as-string
203                 (if (and params (listp (elt params 0)))
204                     (elt params 0)
205                   params))))
206
207 (defun lurk-msg-tags (msg) (elt msg 0))
208 (defun lurk-msg-src (msg) (elt msg 1))
209 (defun lurk-msg-cmd (msg) (elt msg 2))
210 (defun lurk-msg-params (msg) (elt msg 3))
211 (defun lurk-msg-trail (msg)
212   (let ((params (lurk-msg-params msg)))
213     (if params
214         (elt params (- (length params) 1)))))
215
216 (defvar lurk-msg-regex
217   (rx
218    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
219         (* whitespace))
220    (opt (: ":" (: (group (* (not (any space "!" "@"))))
221                   (* (not (any space)))))
222         (* whitespace))
223    (group (: (* (not whitespace))))
224    (* whitespace)
225    (opt (group (+ not-newline))))
226   "Regex used to parse IRC messages.
227 Note that this regex is incomplete.  Noteably, we discard the non-nick
228 portion of the source component of the message, as LURK doesn't use this.")
229
230 (defun lurk-string->msg (string)
231   (if (string-match lurk-msg-regex string)
232       (let* ((tags (match-string 1 string))
233              (src (match-string 2 string))
234              (cmd (upcase (match-string 3 string)))
235              (params-str (match-string 4 string))
236              (params
237               (if params-str
238                   (let* ((idx (cl-search ":" params-str))
239                          (l (split-string (string-trim (substring params-str 0 idx))))
240                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
241                     (append l r))
242                 nil)))
243         (apply #'lurk-msg (append (list tags src cmd) params)))
244     (error "Failed to parse string " string)))
245
246 (defun lurk-msg->string (msg)
247   (let ((tags (lurk-msg-tags msg))
248         (src (lurk-msg-src msg))
249         (cmd (lurk-msg-cmd msg))
250         (params (lurk-msg-params msg)))
251     (lurk--filtered-join
252      (if tags (concat "@" tags) nil)
253      (if src (concat ":" src) nil)
254      cmd
255      (if (> (length params) 1)
256          (string-join (seq-take params (- (length params) 1)) " ")
257        nil)
258      (if (> (length params) 0)
259          (concat ":" (elt params (- (length params) 1)))
260        nil))))
261
262
263 ;;; Contexts
264 ;;
265
266 (defvar lurk-current-context nil)
267 (defvar lurk-contexts (make-hash-table :test #'equal))
268
269 (defun lurk-add-context (name)
270   (puthash name nil lurk-contexts))
271
272 (defun lurk-del-context (name)
273   (remhash name lurk-contexts))
274
275 (defun lurk-get-context-users (name)
276   (gethash name lurk-contexts))
277
278 (defun lurk-add-context-users (context users)
279   (puthash context
280            (append users
281                    (gethash context lurk-contexts))
282            lurk-contexts))
283
284 (defun lurk-del-context-user (context user)
285   (puthash context
286            (remove user (gethash context lurk-contexts))
287            lurk-contexts))
288
289 (defun lurk-del-user (user)
290   (dolist (context (lurk-get-context-list))
291     (lurk-del-context-user context user)))
292
293 (defun lurk-rename-user (old-nick new-nick)
294   (dolist (context (lurk-get-context-list))
295     (lurk-del-context-user context old-nick)
296     (lurk-add-context-users context (list new-nick))))
297
298 (defun lurk-get-context-type (name)
299   (cond
300    ((string-prefix-p "#" name) 'channel)
301    ((string-match-p (rx (or "." "localhost")) name) 'host)
302    (t 'nick)))
303
304 (defun lurk-get-context-list ()
305   (let ((res nil))
306     (maphash (lambda (key val)
307                (cl-pushnew key res))
308              lurk-contexts)
309     res))
310
311 (defun lurk-get-next-context (&optional prev)
312   (if lurk-current-context
313       (let* ((context-list (if prev
314                                (reverse (lurk-get-context-list))
315                              (lurk-get-context-list)))
316              (context-list* (member lurk-current-context context-list)))
317         (if (> (length context-list*) 1)
318             (cadr context-list*)
319           (car context-list)))
320     nil))
321
322 (defun lurk-set-current-context (context)
323   (setq lurk-current-context context)
324   (lurk-highlight-context context)
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       (progn
331         (lurk-set-current-context (lurk-get-next-context rev))
332         (lurk-render-prompt))
333     (lurk-display-error "No channels joined.")))
334
335
336 ;;; Buffer
337 ;;
338
339 (defun lurk-render-prompt ()
340   (with-current-buffer "*lurk*"
341     (let ((update-point (= lurk-input-marker (point)))
342           (update-window-points (mapcar (lambda (w)
343                                           (list (= (window-point w) lurk-input-marker)
344                                                 w))
345                                         (get-buffer-window-list nil nil t))))
346       (save-excursion
347         (set-marker-insertion-type lurk-prompt-marker nil)
348         (set-marker-insertion-type lurk-input-marker t)
349         (let ((inhibit-read-only t))
350           (delete-region lurk-prompt-marker lurk-input-marker)
351           (goto-char lurk-prompt-marker)
352           (insert
353            (propertize (if lurk-current-context
354                            lurk-current-context
355                          "")
356                        'face 'lurk-context
357                        'read-only t)
358            (propertize (concat lurk-prompt-string " ")
359                        'face 'lurk-prompt
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
412 ;;; Output formatting and highlighting
413 ;;
414
415 ;; Idea: the face text property can be a list of faces, applied in
416 ;; order.  By assigning each context a unique list and keeping track
417 ;; of these in a hash table, we can easily switch the face
418 ;; corresponding to a particular context by modifying the elements of
419 ;; this list.
420 ;;
421 ;; More subtly, we make only the cdrs of this list shared among
422 ;; all text of a given context, allowing the cars to be different
423 ;; and for different elements of the context-specific text to have
424 ;; different styling.
425
426 ;; Additionally, we allow selective hiding of contexts via
427 ;; the buffer-invisibility-spec.
428
429 (defvar lurk-context-facelists (make-hash-table :test 'equal)
430   "List of seen contexts and associated face lists.")
431
432 (defun lurk-get-context-facelist (context)
433   (let ((facelist (gethash context lurk-context-facelists)))
434     (unless facelist
435       (setq facelist (list 'lurk-text))
436       (puthash context facelist lurk-context-facelists))
437     facelist))
438
439 (defun lurk--fill-strings (col indent &rest strings)
440   (with-temp-buffer
441     (setq buffer-invisibility-spec nil)
442     (let ((fill-column col)
443           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
444       (apply #'insert strings)
445       (fill-region (point-min) (point-max) nil t)
446       (buffer-string))))
447
448 (defun lurk-display-string (context prefix &rest strings)
449   (with-current-buffer (get-buffer-create "*lurk*")
450     (save-excursion
451       (goto-char lurk-prompt-marker)
452       (let* ((inhibit-read-only t)
453              (old-pos (marker-position lurk-prompt-marker))
454              (padded-timestamp (concat (format-time-string "%H:%M ")))
455              (padded-prefix (if prefix (concat prefix " ") ""))
456              (context-atom (if context (intern context) nil)))
457         (insert-before-markers
458          (lurk--fill-strings
459           80
460           (+ (length padded-timestamp)
461              (length padded-prefix))
462           (propertize padded-timestamp
463                       'face 'lurk-timestamp
464                       'read-only t
465                       'context context
466                       'invisible context-atom)
467           (propertize padded-prefix
468                       'read-only t
469                       'context context
470                       'invisible context-atom)
471           (lurk-add-formatting
472            (propertize (concat (apply #'lurk-buttonify-urls strings) "\n")
473                        'face (lurk-get-context-facelist context)
474                        'read-only t
475                        'context context
476                        'invisible context-atom))))))))
477
478 (defun lurk-display-message (from to text)
479   (let ((context (if (eq 'channel (lurk-get-context-type to))
480                      to
481                    (if (equal to lurk-nick) from to))))
482     (lurk-display-string
483      context
484      (propertize
485       (pcase (lurk-get-context-type to)
486         ('channel (concat to " <" from ">"))
487         ('nick (concat "[" from " -> " to "]"))
488         (_
489          (error "Unsupported context type")))
490       'face (lurk-get-context-facelist context))
491      text)))
492
493 (defun lurk-display-action (from to action-text)
494   (let ((context (if (eq 'channel (lurk-get-context-type to))
495                      to
496                    (if (equal to lurk-nick) from to))))
497     (lurk-display-string
498      context
499      (propertize
500       (concat context " * " from)
501       'face (lurk-get-context-facelist context))
502      action-text)))
503
504 (defun lurk-display-notice (context &rest notices)
505   (lurk-display-string
506    context
507    (propertize lurk-notice-prefix 'face 'lurk-notice)
508    (apply #'concat notices)))
509
510 (defun lurk-display-error (&rest messages)
511   (lurk-display-string
512    nil
513    (propertize lurk-error-prefix 'face 'lurk-error)
514    (apply #'concat messages)))
515
516 (defun lurk-highlight-context (context)
517   (maphash
518    (lambda (this-context facelist)
519      (if (equal this-context context)
520          (setcar facelist 'lurk-text)
521        (setcar facelist 'lurk-faded)))
522    lurk-context-facelists)
523   (force-window-update "*lurk*"))
524
525 (defun lurk-zoom-in (context)
526   (with-current-buffer "*lurk*"
527     (maphash
528      (lambda (this-context _)
529        (when this-context
530          (let ((this-context-atom (intern this-context)))
531            (if (equal this-context context)
532                (remove-from-invisibility-spec this-context-atom)
533              (add-to-invisibility-spec this-context-atom)))))
534      lurk-context-facelists)
535     (force-window-update "*lurk*")))
536
537 (defun lurk-zoom-out ()
538   (with-current-buffer "*lurk*"
539     (maphash
540      (lambda (this-context _)
541        (let ((this-context-atom (if this-context (intern this-context) nil)))
542          (remove-from-invisibility-spec this-context-atom)))
543      lurk-context-facelists)
544     (force-window-update "*lurk*")))
545
546 (defconst lurk-url-regex
547   (rx (:
548        (group (+ alpha))
549        "://"
550        (group (or (+ (any alnum "." "-"))
551                   (+ (any alnum ":"))))
552        (opt (group (: ":" (+ digit))))
553        (opt (group (: "/"
554                       (opt
555                        (* (any alnum "-/.,#:%=&_?~@+"))
556                        (any alnum "-/#:%=&_~@+")))))))
557   "Imperfect regex used to find URLs in plain text.")
558
559 (defun lurk-click-url (button)
560   (browse-url (button-get button 'url)))
561
562 (defun lurk-buttonify-urls (&rest strings)
563   "Turn substrings which look like urls in STRING into clickable buttons."
564   (with-temp-buffer
565     (apply #'insert strings)
566     (goto-char (point-min))
567     (while (re-search-forward lurk-url-regex nil t)
568       (let ((url (match-string 0)))
569         (make-text-button (match-beginning 0)
570                           (match-end 0)
571                           'action #'lurk-click-url
572                           'url url
573                           'follow-link t
574                           'face 'button
575                           'help-echo "Open URL in browser.")))
576     (buffer-string)))
577
578 (defun lurk-add-formatting (string)
579   (with-temp-buffer
580     (insert string)
581     (goto-char (point-min))
582     (let ((bold nil)
583           (italics nil)
584           (underline nil)
585           (strikethrough nil)
586           (prev-point (point)))
587       (while (re-search-forward (rx (any "\x02\x1D\x1F\x1E")) nil t)
588         (let ((beg (+ (match-beginning 0) 1)))
589           (if bold
590               (add-face-text-property prev-point beg '(:weight bold)))
591           (if italics
592               (add-face-text-property prev-point beg '(:slant italic)))
593           (if underline
594               (add-face-text-property prev-point beg '(:underline t)))
595           (if strikethrough
596               (add-face-text-property prev-point beg '(:strike-through t)))
597           (pcase (match-string 0)
598             ("\x02" (setq bold (not bold)))
599             ("\x1D" (setq italics (not italics)))
600             ("\x1F" (setq underline (not underline)))
601             ("\x1E" (setq strikethrough (not strikethrough))))
602           (delete-region (match-beginning 0) (match-end 0))
603           (setq prev-point (point)))))
604     (buffer-string)))
605
606
607 ;;; Message evaluation
608 ;;
609
610 (defun lurk-eval-msg-string (string)
611   (if lurk-debug
612       (lurk-display-string nil nil string))
613   (let* ((msg (lurk-string->msg string)))
614     (lurk-process-autoreplies msg)
615     (pcase (lurk-msg-cmd msg)
616       ("PING"
617        (lurk-send-msg
618         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
619
620       ("PONG")
621
622       ("001"
623        (let* ((params (lurk-msg-params msg))
624               (nick (elt params 0))
625               (text (string-join (seq-drop params 1) " ")))
626          (setq lurk-nick nick)
627          (lurk-display-notice nil text)))
628
629       ("353" ; NAMEREPLY
630        (let* ((params (lurk-msg-params msg))
631               (channel (elt params 2))
632               (names (split-string (elt params 3))))
633          (lurk-add-context-users channel names)))
634
635       ("366" ; ENDOFNAMES
636        (let* ((params (lurk-msg-params msg))
637               (channel (elt params 1)))
638          (lurk-display-notice
639           channel
640           (lurk--as-string (length (lurk-get-context-users channel)))
641           " users in " channel)))
642
643       ("331"
644        (let* ((params (lurk-msg-params msg))
645               (channel (elt params 1)))
646          (lurk-display-notice
647           channel
648           "No topic set.")))
649
650       ("332"
651        (let* ((params (lurk-msg-params msg))
652               (channel (elt params 1))
653               (topic (elt params 2)))
654          (lurk-display-notice channel "Topic: " topic)))
655
656       ("333") ; Avoid displaying these
657
658       ((rx (= 3 (any digit)))
659        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
660
661       ((and "JOIN"
662             (guard (equal lurk-nick (lurk-msg-src msg))))
663        (let ((channel (car (lurk-msg-params msg))))
664          (lurk-add-context channel)
665          (lurk-set-current-context channel)
666          (lurk-display-notice channel "Joining channel " channel)
667          (lurk-render-prompt)))
668
669       ("JOIN"
670        (let ((channel (car (lurk-msg-params msg)))
671              (nick (lurk-msg-src msg)))
672          (lurk-add-context-users channel (list nick))
673          (if lurk-show-joins
674              (lurk-display-notice channel nick " joined channel " channel))))
675
676       ((and "PART"
677             (guard (equal lurk-nick (lurk-msg-src msg))))
678        (let ((channel (car (lurk-msg-params msg))))
679          (lurk-display-notice channel "Left channel " channel)
680          (lurk-del-context channel)
681          (if (equal channel lurk-current-context)
682              (lurk-set-current-context (lurk-get-next-context)))
683          (lurk-render-prompt)))
684
685       ("PART"
686        (let ((channel (car (lurk-msg-params msg)))
687              (nick (lurk-msg-src msg)))
688          (lurk-del-context-user channel nick)
689          (if lurk-show-joins
690              (lurk-display-notice channel nick " left channel " channel))))
691
692       ((and "KICK")
693        (let ((kicker-nick (lurk-msg-src msg))
694              (channel (car (lurk-msg-params msg)))
695              (nick (cadr (lurk-msg-params msg)))
696              (reason (caddr (lurk-msg-params msg))))
697          (if (equal nick lurk-nick)
698              (progn
699                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
700                (lurk-del-context channel)
701                (if (equal channel lurk-current-context)
702                    (lurk-set-current-context (lurk-get-next-context)))
703                (lurk-render-prompt))
704            (lurk-del-context-user channel nick)
705            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
706
707       ("QUIT"
708        (let ((nick (lurk-msg-src msg))
709              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
710          (lurk-del-user nick)
711          (if lurk-show-joins
712              (lurk-display-notice nil nick " quit: " reason))))
713
714       ((and "NICK"
715             (guard (equal lurk-nick (lurk-msg-src msg))))
716        (setq lurk-nick (car (lurk-msg-params msg)))
717        (lurk-display-notice nil "Set nick to " lurk-nick))
718
719       ("NICK"
720        (let ((old-nick (lurk-msg-src msg))
721              (new-nick (car (lurk-msg-params msg))))
722          (lurk-display-notice nil old-nick " is now known as " new-nick)
723          (lurk-rename-user old-nick new-nick)))
724
725       ("NOTICE"
726        (let ((nick (lurk-msg-src msg))
727              (channel (car (lurk-msg-params msg)))
728              (text (cadr (lurk-msg-params msg))))
729          (pcase text
730            ((rx (: "\01VERSION "
731                    (let version (* (not "\01")))
732                    "\01"))
733             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
734            (_
735             (lurk-display-notice nil text)))))
736
737       ("PRIVMSG"
738        (let* ((from (lurk-msg-src msg))
739               (params (lurk-msg-params msg))
740               (to (car params))
741               (text (cadr params)))
742          (pcase text
743            ("\01VERSION\01"
744             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
745               (lurk-send-msg (lurk-msg nil nil "NOTICE"
746                                        (list from (concat "\01VERSION "
747                                                           version-string
748                                                           "\01")))))
749             (lurk-display-notice nil "CTCP version request received from " from))
750
751            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
752             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
753             (lurk-display-notice from "CTCP ping received from " from))
754
755            ("\01USERINFO\01"
756             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
757
758            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
759             (lurk-display-action from to action-text))
760
761            (_
762             (lurk-display-message from to text)))))
763       (_
764        (lurk-display-notice nil (lurk-msg->string msg))))))
765
766
767 ;;; User-defined responses
768
769
770 (defvar lurk-autoreply-table nil
771   "Table of autoreply messages.
772
773 Each autoreply is a list of two elements: (matcher reply)
774
775 Here matcher is a list:
776
777 (network src cmd params ...)
778
779 and reply is another list:
780
781  (cmd params ...)
782
783 Each entry in the matcher list is a regular expression tested against the
784 corresponding values in the incomming message.  Entries can be nil,
785 in which case they match anything.")
786
787 (defun lurk--lists-equal (l1 l2)
788     (if (and l1 l2)
789         (if (or (not (and (car l1) (car l2)))
790                 (string-match (car l1) (car l2)))
791             (lurk--lists-equal (cdr l1) (cdr l2))
792           nil)
793       t))
794
795 (defun lurk-process-autoreply (msg autoreply)
796   (let ((matcher (car autoreply))
797         (reply (cadr autoreply)))
798     (let ((network (car matcher)))
799       (when (and (or (not network)
800                      (and (get-process "lurk")
801                           (equal (car (process-contact (get-process "lurk")))
802                                  (cadr (assoc network lurk-networks)))))
803                  (lurk--lists-equal (cdr matcher)
804                                     (append (list (lurk-msg-src msg)
805                                                   (lurk-msg-cmd msg))
806                                             (lurk-msg-params msg))))
807         (lurk-send-msg
808          (lurk-msg nil nil (car reply) (cdr reply)))))))
809
810 (defun lurk-process-autoreplies (msg)
811   (mapc
812    (lambda (autoreply)
813      (lurk-process-autoreply msg autoreply))
814    lurk-autoreply-table))
815
816 ;;; Command entering
817 ;;
818
819 (defun lurk-enter-string (string)
820   (if (string-prefix-p "/" string)
821       (pcase (substring string 1)
822         ((rx (: "DEBUG" (opt (: " " (let setting (or "ON" "OFF"))))))
823          (setq lurk-debug
824                (if setting
825                    (if (equal (upcase setting) "ON")
826                        t
827                      nil)
828                  (not lurk-debug)))
829          (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
830
831         ((rx "HEADER")
832          (if header-line-format
833            (progn
834              (setq-local header-line-format nil)
835              (lurk-display-notice nil "Header disabled."))
836            (lurk-setup-header)
837            (lurk-display-notice nil "Header enabled.")))
838
839         ((rx (: "CONNECT " (let network (* not-newline))))
840          (lurk-display-notice nil "Attempting to connect to " network "...")
841          (lurk-connect network))
842
843         ((rx (: "TOPIC " (let new-topic (* not-newline))))
844          (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context new-topic)))
845
846         ((rx (: "ME " (let action (* not-newline))))
847          (let ((ctcp-text (concat "\01ACTION " action "\01")))
848            (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
849                                     (list lurk-current-context ctcp-text)))
850            (lurk-display-action lurk-nick lurk-current-context action)))
851
852         ((rx (: "VERSION" " " (let nick (+ (not whitespace)))))
853          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
854                                   (list nick "\01VERSION\01")))
855          (lurk-display-notice nil "CTCP version request sent to " nick))
856
857         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
858          (if (or lurk-current-context channel)
859              (lurk-send-msg (lurk-msg nil nil "PART" (if channel
860                                                          channel
861                                                        lurk-current-context)))
862            (lurk-display-error "No current channel to leave.")))
863
864         ((rx "QUIT" (opt (: " " (let quit-msg (* not-newline)))))
865          (lurk-send-msg (lurk-msg nil nil "QUIT"
866                                   (or quit-msg lurk-default-quit-msg))))
867
868         ((rx (: "NICK" (* whitespace) string-end))
869          (lurk-display-notice nil "Current nick: " lurk-nick))
870
871         ((rx (: "NICK" (+ whitespace) (let nick (+ (not whitespace)))))
872          (if (lurk-connected-p)
873              (lurk-send-msg (lurk-msg nil nil "NICK" nick))
874            (setq lurk-nick nick)
875            (lurk-display-notice nil "Set default nick to '" nick "'")))
876
877         ((rx (: "LIST" (* whitespace) string-end))
878          (lurk-display-notice nil "This command can generate lots of output. Use `LIST -yes' if you're sure."))
879
880         ((rx (: "LIST" (+ whitespace) "-YES" (* whitespace) string-end))
881          (lurk-send-msg (lurk-msg nil nil "LIST")))
882
883         ((rx "MSG "
884              (let to (* (not whitespace)))
885              " "
886              (let text (* not-newline)))
887          (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
888          (lurk-display-message lurk-nick to text))
889
890         ((rx (: (let cmd-str (+ (not whitespace)))
891                 (opt (: " " (let params-str (* not-newline))))))
892          (lurk-send-msg (lurk-msg nil nil (upcase cmd-str)
893                                   (if params-str
894                                       (split-string params-str)
895                                     nil)))))
896
897     (unless (string-empty-p string)
898       (if lurk-current-context
899           (progn
900             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
901                                      lurk-current-context
902                                      string))
903             (lurk-display-message lurk-nick lurk-current-context string))
904         (lurk-display-error "No current context.")))))
905
906 (defvar lurk-history nil
907   "Commands and messages sent in current session.")
908
909
910 (defun lurk-enter ()
911   "Enter current contents of line after prompt."
912   (interactive)
913   (with-current-buffer "*lurk*"
914     (let ((line (buffer-substring lurk-input-marker (point-max))))
915       (push line lurk-history)
916       (setq lurk-history-index nil)
917       (let ((inhibit-read-only t))
918         (delete-region lurk-input-marker (point-max)))
919       (lurk-enter-string line))))
920
921 (defvar lurk-history-index nil)
922
923 (defun lurk-history-cycle (delta)
924   (when lurk-history
925     (with-current-buffer "*lurk*"
926       (if lurk-history-index
927           (setq lurk-history-index
928                 (max 0
929                      (min (- (length lurk-history) 1)
930                           (+ delta lurk-history-index))))
931         (setq lurk-history-index 0))
932       (delete-region lurk-input-marker (point-max))
933       (insert (elt lurk-history lurk-history-index)))))
934
935 (defun lurk-history-next ()
936   (interactive)
937   (lurk-history-cycle -1))
938
939 (defun lurk-history-prev ()
940   (interactive)
941   (lurk-history-cycle +1))
942
943 ;;; Interactive functions
944 ;;
945
946 (defun lurk-cycle-contexts-forward ()
947   (interactive)
948   (lurk-cycle-contexts))
949
950 (defun lurk-cycle-contexts-reverse ()
951   (interactive)
952   (lurk-cycle-contexts t))
953
954 (defvar lurk-zoomed nil
955   "Keeps track of zoom status.")
956
957 (defun lurk-toggle-zoom ()
958   (interactive)
959   (if lurk-zoomed
960       (lurk-zoom-out)
961     (lurk-zoom-in lurk-current-context))
962   (setq lurk-zoomed (not lurk-zoomed)))
963
964 (defun lurk-complete-nick ()
965   (interactive)
966   (when (and (>= (point) lurk-input-marker) lurk-current-context)
967     (let* ((end (max lurk-input-marker (point)))
968            (space-idx (save-excursion
969                         (re-search-backward " " lurk-input-marker t)))
970            (start (if space-idx (+ 1 space-idx) lurk-input-marker))
971            (completion-ignore-case t))
972       (unless (string-prefix-p "/" (buffer-substring start end))
973         (completion-in-region start end (lurk-get-context-users lurk-current-context))))))
974
975
976 ;;; Mode
977 ;;
978
979 (defvar lurk-mode-map
980   (let ((map (make-sparse-keymap)))
981     (define-key map (kbd "RET") 'lurk-enter)
982     (define-key map (kbd "<tab>") 'lurk-complete-nick)
983     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
984     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
985     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
986     (define-key map (kbd "<C-up>") 'lurk-history-prev)
987     (define-key map (kbd "<C-down>") 'lurk-history-next)
988     ;; (when (fboundp 'evil-define-key*)
989     ;;   (evil-define-key* 'insert map
990     ;;                     (kbd "<C-Up>") 'lurk-history-prev
991     ;;                     (kbd "<C-Down>") 'lurk-history-next))
992     map))
993
994 (defvar lurk-mode-map)
995
996 (define-derived-mode lurk-mode text-mode "lurk"
997   "Major mode for LURK.")
998
999 (when (fboundp 'evil-set-initial-state)
1000   (evil-set-initial-state 'lurk-mode 'insert))
1001
1002 ;;; Main start procedure
1003 ;;
1004
1005 (defun lurk ()
1006   "Switch to *lurk* buffer."
1007   (interactive)
1008   (if (get-buffer "*lurk*")
1009       (switch-to-buffer "*lurk*")
1010     (switch-to-buffer "*lurk*")
1011     (lurk-mode)
1012     (lurk-setup-buffer))
1013   "Started LURK.")
1014
1015
1016 ;;; lurk.el ends here