Network names now complete.
[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 org-priority))
69   "Face used for the prompt.")
70
71 (defface lurk-context
72   '((t :inherit org-tag))
73   "Face used for the context name in the prompt.")
74
75 (defface lurk-faded
76   '((t :inherit org-agenda-dimmed-todo-face))
77   "Face used for faded Lurk text.")
78
79 (defface lurk-timestamp
80   '((t :inherit org-agenda-dimmed-todo-face))
81   "Face used for timestamps.")
82
83 (defface lurk-error
84   '((t :inherit font-lock-regexp-grouping-construct))
85   "Face used for Lurk error text.")
86
87 (defface lurk-notice
88   '((t :inherit org-upcoming-deadline))
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-add-context-users (context users)
275   (puthash context
276            (append users
277                    (gethash context lurk-contexts))
278            lurk-contexts))
279
280 (defun lurk-del-context-user (context user)
281   (puthash context
282            (remove user (gethash context lurk-contexts))
283            lurk-contexts))
284
285 (defun lurk-del-user (user)
286   (dolist (context (lurk-get-context-list))
287     (lurk-del-context-user context user)))
288
289 (defun lurk-rename-user (old-nick new-nick)
290   (dolist (context (lurk-get-context-list))
291     (lurk-del-context-user context old-nick)
292     (lurk-add-context-users context (list new-nick))))
293
294 (defun lurk-get-context-type (name)
295   (cond
296    ((string-prefix-p "#" name) 'channel)
297    ((string-match-p (rx (or "." "localhost")) name) 'host)
298    (t 'nick)))
299
300 (defun lurk-get-context-list ()
301   (let ((res nil))
302     (maphash (lambda (key val)
303                (cl-pushnew key res))
304              lurk-contexts)
305     res))
306
307 (defun lurk-get-next-context (&optional prev)
308   (if lurk-current-context
309       (let* ((context-list (if prev
310                                (reverse (lurk-get-context-list))
311                              (lurk-get-context-list)))
312              (context-list* (member lurk-current-context context-list)))
313         (if (> (length context-list*) 1)
314             (cadr context-list*)
315           (car context-list)))
316     nil))
317
318 (defun lurk-set-current-context (context)
319   (setq lurk-current-context context)
320   (lurk-highlight-context context)
321   (if lurk-zoomed
322       (lurk-zoom-in lurk-current-context)))
323
324 (defun lurk-cycle-contexts (&optional rev)
325   (if lurk-current-context
326       (progn
327         (lurk-set-current-context (lurk-get-next-context rev))
328         (lurk-render-prompt))
329     (lurk-display-error "No channels joined.")))
330
331
332 ;;; Buffer
333 ;;
334
335 (defun lurk-render-prompt ()
336   (with-current-buffer "*lurk*"
337     (let ((update-point (= lurk-input-marker (point)))
338           (update-window-points (mapcar (lambda (w)
339                                           (list (= (window-point w) lurk-input-marker)
340                                                 w))
341                                         (get-buffer-window-list nil nil t))))
342       (save-excursion
343         (set-marker-insertion-type lurk-prompt-marker nil)
344         (set-marker-insertion-type lurk-input-marker t)
345         (let ((inhibit-read-only t))
346           (delete-region lurk-prompt-marker lurk-input-marker)
347           (goto-char lurk-prompt-marker)
348           (insert
349            (propertize (if lurk-current-context
350                            lurk-current-context
351                          "")
352                        'face 'lurk-context
353                        'read-only t)
354            (propertize (concat lurk-prompt-string " ")
355                        'face 'lurk-prompt
356                        'read-only t
357                        'rear-nonsticky t)))
358         (set-marker-insertion-type lurk-input-marker nil))
359       (if update-point
360           (goto-char lurk-input-marker))
361       (dolist (v update-window-points)
362         (if (car v)
363             (set-window-point (cadr v) lurk-input-marker))))))
364   
365 (defvar lurk-prompt-marker nil
366   "Marker for prompt position in LURK buffer.")
367
368 (defvar lurk-input-marker nil
369   "Marker for prompt position in LURK buffer.")
370
371 (defun lurk-setup-header ()
372   (with-current-buffer "*lurk*"
373     (setq-local header-line-format
374                 '((:eval
375                    (let ((proc (get-process "lurk")))
376                      (if proc
377                          (concat
378                           "Host: " (car (process-contact proc))
379                           ", Context: "
380                           (if lurk-current-context
381                               (concat
382                                lurk-current-context
383                                " ("
384                                (number-to-string
385                                 (length (lurk-get-context-users lurk-current-context)))
386                                " users)")
387                             "Server"))
388                        "No connection")))
389                   (:eval
390                    (if lurk-zoomed " [ZOOMED]" ""))))))
391
392 (defun lurk-setup-buffer ()
393   (with-current-buffer (get-buffer-create "*lurk*")
394     (setq-local scroll-conservatively 1)
395     (setq-local buffer-invisibility-spec nil)
396     (if (markerp lurk-prompt-marker)
397         (set-marker lurk-prompt-marker (point-max))
398       (setq lurk-prompt-marker (point-max-marker)))
399     (if (markerp lurk-input-marker)
400         (set-marker lurk-input-marker (point-max))
401       (setq lurk-input-marker (point-max-marker)))
402     (goto-char (point-max))
403     (lurk-render-prompt)
404     (if lurk-display-header
405         (lurk-setup-header))))
406
407
408 ;;; Output formatting and highlighting
409 ;;
410
411 ;; Idea: the face text property can be a list of faces, applied in
412 ;; order.  By assigning each context a unique list and keeping track
413 ;; of these in a hash table, we can easily switch the face
414 ;; corresponding to a particular context by modifying the elements of
415 ;; this list.
416 ;;
417 ;; More subtly, we make only the cdrs of this list shared among
418 ;; all text of a given context, allowing the cars to be different
419 ;; and for different elements of the context-specific text to have
420 ;; different styling.
421
422 ;; Additionally, we allow selective hiding of contexts via
423 ;; the buffer-invisibility-spec.
424
425 (defvar lurk-context-facelists (make-hash-table :test 'equal)
426   "List of seen contexts and associated face lists.")
427
428 (defun lurk-get-context-facelist (context)
429   (let ((facelist (gethash context lurk-context-facelists)))
430     (unless facelist
431       (setq facelist (list 'lurk-text))
432       (puthash context facelist lurk-context-facelists))
433     facelist))
434
435 (defun lurk--fill-strings (col indent &rest strings)
436   (with-temp-buffer
437     (setq buffer-invisibility-spec nil)
438     (let ((fill-column col)
439           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
440       (apply #'insert strings)
441       (fill-region (point-min) (point-max) nil t)
442       (buffer-string))))
443
444 (defun lurk-display-string (context prefix &rest strings)
445   (with-current-buffer (get-buffer-create "*lurk*")
446     (save-excursion
447       (goto-char lurk-prompt-marker)
448       (let* ((inhibit-read-only t)
449              (old-pos (marker-position lurk-prompt-marker))
450              (padded-timestamp (concat (format-time-string "%H:%M ")))
451              (padded-prefix (if prefix (concat prefix " ") ""))
452              (context-atom (if context (intern context) nil)))
453         (insert-before-markers
454          (lurk--fill-strings
455           80
456           (+ (length padded-timestamp)
457              (length padded-prefix))
458           (propertize padded-timestamp
459                       'face 'lurk-timestamp
460                       'read-only t
461                       'context context
462                       'invisible context-atom)
463           (propertize padded-prefix
464                       'read-only t
465                       'context context
466                       'invisible context-atom)
467           (lurk-add-formatting
468            (propertize (concat (apply #'lurk-buttonify-urls strings) "\n")
469                        'face (lurk-get-context-facelist context)
470                        'read-only t
471                        'context context
472                        'invisible context-atom))))))))
473
474 (defun lurk-display-message (from to text)
475   (let ((context (if (eq 'channel (lurk-get-context-type to))
476                      to
477                    (if (equal to lurk-nick) from to))))
478     (lurk-display-string
479      context
480      (propertize
481       (pcase (lurk-get-context-type to)
482         ('channel (concat to " <" from ">"))
483         ('nick (concat "[" from " -> " to "]"))
484         (_
485          (error "Unsupported context type")))
486       'face (lurk-get-context-facelist context))
487      text)))
488
489 (defun lurk-display-action (from to action-text)
490   (let ((context (if (eq 'channel (lurk-get-context-type to))
491                      to
492                    (if (equal to lurk-nick) from to))))
493     (lurk-display-string
494      context
495      (propertize
496       (concat context " * " from)
497       'face (lurk-get-context-facelist context))
498      action-text)))
499
500 (defun lurk-display-notice (context &rest notices)
501   (lurk-display-string
502    context
503    (propertize lurk-notice-prefix 'face 'lurk-notice)
504    (apply #'concat notices)))
505
506 (defun lurk-display-error (&rest messages)
507   (lurk-display-string
508    nil
509    (propertize lurk-error-prefix 'face 'lurk-error)
510    (apply #'concat messages)))
511
512 (defun lurk-highlight-context (context)
513   (maphash
514    (lambda (this-context facelist)
515      (if (equal this-context context)
516          (setcar facelist 'lurk-text)
517        (setcar facelist 'lurk-faded)))
518    lurk-context-facelists)
519   (force-window-update "*lurk*"))
520
521 (defun lurk-zoom-in (context)
522   (with-current-buffer "*lurk*"
523     (maphash
524      (lambda (this-context _)
525        (when this-context
526          (let ((this-context-atom (intern this-context)))
527            (if (equal this-context context)
528                (remove-from-invisibility-spec this-context-atom)
529              (add-to-invisibility-spec this-context-atom)))))
530      lurk-context-facelists)
531     (force-window-update "*lurk*")))
532
533 (defun lurk-zoom-out ()
534   (with-current-buffer "*lurk*"
535     (maphash
536      (lambda (this-context _)
537        (let ((this-context-atom (if this-context (intern this-context) nil)))
538          (remove-from-invisibility-spec this-context-atom)))
539      lurk-context-facelists)
540     (force-window-update "*lurk*")))
541
542 (defconst lurk-url-regex
543   (rx (:
544        (group (+ alpha))
545        "://"
546        (group (or (+ (any alnum "." "-"))
547                   (+ (any alnum ":"))))
548        (opt (group (: ":" (+ digit))))
549        (opt (group (: "/"
550                       (opt
551                        (* (any alnum "-/.,#:%=&_?~@+"))
552                        (any alnum "-/#:%=&_~@+")))))))
553   "Imperfect regex used to find URLs in plain text.")
554
555 (defun lurk-click-url (button)
556   (browse-url (button-get button 'url)))
557
558 (defun lurk-buttonify-urls (&rest strings)
559   "Turn substrings which look like urls in STRING into clickable buttons."
560   (with-temp-buffer
561     (apply #'insert strings)
562     (goto-char (point-min))
563     (while (re-search-forward lurk-url-regex nil t)
564       (let ((url (match-string 0)))
565         (make-text-button (match-beginning 0)
566                           (match-end 0)
567                           'action #'lurk-click-url
568                           'url url
569                           'follow-link t
570                           'face 'button
571                           'help-echo "Open URL in browser.")))
572     (buffer-string)))
573
574 (defun lurk-add-formatting (string)
575   (with-temp-buffer
576     (insert string)
577     (goto-char (point-min))
578     (let ((bold nil)
579           (italics nil)
580           (underline nil)
581           (strikethrough nil)
582           (prev-point (point)))
583       (while (re-search-forward (rx (any "\x02\x1D\x1F\x1E")) nil t)
584         (let ((beg (+ (match-beginning 0) 1)))
585           (if bold
586               (add-face-text-property prev-point beg '(:weight bold)))
587           (if italics
588               (add-face-text-property prev-point beg '(:slant italic)))
589           (if underline
590               (add-face-text-property prev-point beg '(:underline t)))
591           (if strikethrough
592               (add-face-text-property prev-point beg '(:strike-through t)))
593           (pcase (match-string 0)
594             ("\x02" (setq bold (not bold)))
595             ("\x1D" (setq italics (not italics)))
596             ("\x1F" (setq underline (not underline)))
597             ("\x1E" (setq strikethrough (not strikethrough))))
598           (delete-region (match-beginning 0) (match-end 0))
599           (setq prev-point (point)))))
600     (buffer-string)))
601
602
603 ;;; Message evaluation
604 ;;
605
606 (defun lurk-eval-msg-string (string)
607   (if lurk-debug
608       (lurk-display-string nil nil string))
609   (let* ((msg (lurk-string->msg string)))
610     (lurk-process-autoreplies msg)
611     (pcase (lurk-msg-cmd msg)
612       ("PING"
613        (lurk-send-msg
614         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
615
616       ("PONG")
617
618       ("001"
619        (let* ((params (lurk-msg-params msg))
620               (nick (elt params 0))
621               (text (string-join (seq-drop params 1) " ")))
622          (setq lurk-nick nick)
623          (lurk-display-notice nil text)))
624
625       ("353" ; NAMEREPLY
626        (let* ((params (lurk-msg-params msg))
627               (channel (elt params 2))
628               (names (split-string (elt params 3))))
629          (lurk-add-context-users channel names)))
630
631       ("366" ; ENDOFNAMES
632        (let* ((params (lurk-msg-params msg))
633               (channel (elt params 1)))
634          (lurk-display-notice
635           channel
636           (lurk--as-string (length (lurk-get-context-users channel)))
637           " users in " channel)))
638
639       ("331"
640        (let* ((params (lurk-msg-params msg))
641               (channel (elt params 1)))
642          (lurk-display-notice
643           channel
644           "No topic set.")))
645
646       ("332"
647        (let* ((params (lurk-msg-params msg))
648               (channel (elt params 1))
649               (topic (elt params 2)))
650          (lurk-display-notice channel "Topic: " topic)))
651
652       ("333") ; Avoid displaying these
653
654       ((rx (= 3 (any digit)))
655        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
656
657       ((and "JOIN"
658             (guard (equal lurk-nick (lurk-msg-src msg))))
659        (let ((channel (car (lurk-msg-params msg))))
660          (lurk-add-context channel)
661          (lurk-set-current-context channel)
662          (lurk-display-notice channel "Joining channel " channel)
663          (lurk-render-prompt)))
664
665       ("JOIN"
666        (let ((channel (car (lurk-msg-params msg)))
667              (nick (lurk-msg-src msg)))
668          (lurk-add-context-users channel (list nick))
669          (if lurk-show-joins
670              (lurk-display-notice channel nick " joined channel " channel))))
671
672       ((and "PART"
673             (guard (equal lurk-nick (lurk-msg-src msg))))
674        (let ((channel (car (lurk-msg-params msg))))
675          (lurk-display-notice channel "Left channel " channel)
676          (lurk-del-context channel)
677          (if (equal channel lurk-current-context)
678              (lurk-set-current-context (lurk-get-next-context)))
679          (lurk-render-prompt)))
680
681       ("PART"
682        (let ((channel (car (lurk-msg-params msg)))
683              (nick (lurk-msg-src msg)))
684          (lurk-del-context-user channel nick)
685          (if lurk-show-joins
686              (lurk-display-notice channel nick " left channel " channel))))
687
688       ((and "KICK")
689        (let ((kicker-nick (lurk-msg-src msg))
690              (channel (car (lurk-msg-params msg)))
691              (nick (cadr (lurk-msg-params msg)))
692              (reason (caddr (lurk-msg-params msg))))
693          (if (equal nick lurk-nick)
694              (progn
695                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
696                (lurk-del-context channel)
697                (if (equal channel lurk-current-context)
698                    (lurk-set-current-context (lurk-get-next-context)))
699                (lurk-render-prompt))
700            (lurk-del-context-user channel nick)
701            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
702
703       ("QUIT"
704        (let ((nick (lurk-msg-src msg))
705              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
706          (lurk-del-user nick)
707          (if lurk-show-joins
708              (lurk-display-notice nil nick " quit: " reason))))
709
710       ((and "NICK"
711             (guard (equal lurk-nick (lurk-msg-src msg))))
712        (setq lurk-nick (car (lurk-msg-params msg)))
713        (lurk-display-notice nil "Set nick to " lurk-nick))
714
715       ("NICK"
716        (let ((old-nick (lurk-msg-src msg))
717              (new-nick (car (lurk-msg-params msg))))
718          (lurk-display-notice nil old-nick " is now known as " new-nick)
719          (lurk-rename-user old-nick new-nick)))
720
721       ("NOTICE"
722        (let ((nick (lurk-msg-src msg))
723              (channel (car (lurk-msg-params msg)))
724              (text (cadr (lurk-msg-params msg))))
725          (pcase text
726            ((rx (: "\01VERSION "
727                    (let version (* (not "\01")))
728                    "\01"))
729             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
730            (_
731             (lurk-display-notice nil text)))))
732
733       ("PRIVMSG"
734        (let* ((from (lurk-msg-src msg))
735               (params (lurk-msg-params msg))
736               (to (car params))
737               (text (cadr params)))
738          (pcase text
739            ("\01VERSION\01"
740             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
741               (lurk-send-msg (lurk-msg nil nil "NOTICE"
742                                        (list from (concat "\01VERSION "
743                                                           version-string
744                                                           "\01")))))
745             (lurk-display-notice nil "CTCP version request received from " from))
746
747            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
748             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
749             (lurk-display-notice from "CTCP ping received from " from))
750
751            ("\01USERINFO\01"
752             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
753
754            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
755             (lurk-display-action from to action-text))
756
757            (_
758             (lurk-display-message from to text)))))
759       (_
760        (lurk-display-notice nil (lurk-msg->string msg))))))
761
762
763 ;;; User-defined responses
764
765
766 (defvar lurk-autoreply-table nil
767   "Table of autoreply messages.
768
769 Each autoreply is a list of two elements: (matcher reply)
770
771 Here matcher is a list:
772
773 (network src cmd params ...)
774
775 and reply is another list:
776
777  (cmd params ...)
778
779 Each entry in the matcher list is a regular expression tested against the
780 corresponding values in the incomming message.  Entries can be nil,
781 in which case they match anything.")
782
783 (defun lurk--lists-equal (l1 l2)
784     (if (and l1 l2)
785         (if (or (not (and (car l1) (car l2)))
786                 (string-match (car l1) (car l2)))
787             (lurk--lists-equal (cdr l1) (cdr l2))
788           nil)
789       t))
790
791 (defun lurk-process-autoreply (msg autoreply)
792   (let ((matcher (car autoreply))
793         (reply (cadr autoreply)))
794     (let ((network (car matcher)))
795       (when (and (or (not network)
796                      (and (get-process "lurk")
797                           (equal (car (process-contact (get-process "lurk")))
798                                  (cadr (assoc network lurk-networks)))))
799                  (lurk--lists-equal (cdr matcher)
800                                     (append (list (lurk-msg-src msg)
801                                                   (lurk-msg-cmd msg))
802                                             (lurk-msg-params msg))))
803         (lurk-send-msg
804          (lurk-msg nil nil (car reply) (cdr reply)))))))
805
806 (defun lurk-process-autoreplies (msg)
807   (mapc
808    (lambda (autoreply)
809      (lurk-process-autoreply msg autoreply))
810    lurk-autoreply-table))
811
812 ;;; Command entering
813 ;;
814
815 (defun lurk-enter-string (string)
816   (if (string-prefix-p "/" string)
817       (pcase (substring string 1)
818         ((rx (: "DEBUG" (opt (: " " (let setting (or "ON" "OFF"))))))
819          (setq lurk-debug
820                (if setting
821                    (if (equal (upcase setting) "ON")
822                        t
823                      nil)
824                  (not lurk-debug)))
825          (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
826
827         ((rx "HEADER")
828          (if header-line-format
829            (progn
830              (setq-local header-line-format nil)
831              (lurk-display-notice nil "Header disabled."))
832            (lurk-setup-header)
833            (lurk-display-notice nil "Header enabled.")))
834
835         ((rx (: "CONNECT " (let network (* not-newline))))
836          (lurk-display-notice nil "Attempting to connect to " network "...")
837          (lurk-connect network))
838
839         ((rx (: "TOPIC " (let new-topic (* not-newline))))
840          (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context new-topic)))
841
842         ((rx (: "ME " (let action (* not-newline))))
843          (let ((ctcp-text (concat "\01ACTION " action "\01")))
844            (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
845                                     (list lurk-current-context ctcp-text)))
846            (lurk-display-action lurk-nick lurk-current-context action)))
847
848         ((rx (: "VERSION" " " (let nick (+ (not whitespace)))))
849          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
850                                   (list nick "\01VERSION\01")))
851          (lurk-display-notice nil "CTCP version request sent to " nick))
852
853         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
854          (if (or lurk-current-context channel)
855              (lurk-send-msg (lurk-msg nil nil "PART" (if channel
856                                                          channel
857                                                        lurk-current-context)))
858            (lurk-display-error "No current channel to leave.")))
859
860         ((rx "QUIT" (opt (: " " (let quit-msg (* not-newline)))))
861          (lurk-send-msg (lurk-msg nil nil "QUIT"
862                                   (or quit-msg lurk-default-quit-msg))))
863
864         ((rx (: "NICK" (* whitespace) string-end))
865          (lurk-display-notice nil "Current nick: " lurk-nick))
866
867         ((rx (: "NICK" (+ whitespace) (let nick (+ (not whitespace)))))
868          (if (lurk-connected-p)
869              (lurk-send-msg (lurk-msg nil nil "NICK" nick))
870            (setq lurk-nick nick)
871            (lurk-display-notice nil "Set default nick to '" nick "'")))
872
873         ((rx (: "LIST" (* whitespace) string-end))
874          (lurk-display-notice nil "This command can generate lots of output. Use `LIST -yes' if you're sure."))
875
876         ((rx (: "LIST" (+ whitespace) "-YES" (* whitespace) string-end))
877          (lurk-send-msg (lurk-msg nil nil "LIST")))
878
879         ((rx "MSG "
880              (let to (* (not whitespace)))
881              " "
882              (let text (* not-newline)))
883          (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
884          (lurk-display-message lurk-nick to text))
885
886         ((rx (: (let cmd-str (+ (not whitespace)))
887                 (opt (: " " (let params-str (* not-newline))))))
888          (lurk-send-msg (lurk-msg nil nil (upcase cmd-str)
889                                   (if params-str
890                                       (split-string params-str)
891                                     nil)))))
892
893     (unless (string-empty-p string)
894       (if lurk-current-context
895           (progn
896             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
897                                      lurk-current-context
898                                      string))
899             (lurk-display-message lurk-nick lurk-current-context string))
900         (lurk-display-error "No current context.")))))
901
902 (defvar lurk-history nil
903   "Commands and messages sent in current session.")
904
905
906 (defun lurk-enter ()
907   "Enter current contents of line after prompt."
908   (interactive)
909   (with-current-buffer "*lurk*"
910     (let ((line (buffer-substring lurk-input-marker (point-max))))
911       (push line lurk-history)
912       (setq lurk-history-index nil)
913       (let ((inhibit-read-only t))
914         (delete-region lurk-input-marker (point-max)))
915       (lurk-enter-string line))))
916
917 (defvar lurk-history-index nil)
918
919 (defun lurk-history-cycle (delta)
920   (when lurk-history
921     (with-current-buffer "*lurk*"
922       (if lurk-history-index
923           (setq lurk-history-index
924                 (max 0
925                      (min (- (length lurk-history) 1)
926                           (+ delta lurk-history-index))))
927         (setq lurk-history-index 0))
928       (delete-region lurk-input-marker (point-max))
929       (insert (elt lurk-history lurk-history-index)))))
930
931 (defun lurk-history-next ()
932   (interactive)
933   (lurk-history-cycle -1))
934
935 (defun lurk-history-prev ()
936   (interactive)
937   (lurk-history-cycle +1))
938
939 ;;; Interactive functions
940 ;;
941
942 (defun lurk-cycle-contexts-forward ()
943   (interactive)
944   (lurk-cycle-contexts))
945
946 (defun lurk-cycle-contexts-reverse ()
947   (interactive)
948   (lurk-cycle-contexts t))
949
950 (defvar lurk-zoomed nil
951   "Keeps track of zoom status.")
952
953 (defun lurk-toggle-zoom ()
954   (interactive)
955   (if lurk-zoomed
956       (lurk-zoom-out)
957     (lurk-zoom-in lurk-current-context))
958   (setq lurk-zoomed (not lurk-zoomed)))
959
960 (defun lurk-complete-input ()
961   (interactive)
962   (when (and (>= (point) lurk-input-marker))
963     (pcase (buffer-substring lurk-input-marker (point))
964       ((rx (: "/connect" (+ " ")
965               (opt (let network (* (not whitespace))))
966               string-end))
967        (let ((space-idx (save-excursion
968                           (re-search-backward " " lurk-input-marker t))))
969          (completion-in-region (+ 1 space-idx)
970                                (point)
971                                (mapcar (lambda (row) (car row)) lurk-networks))))
972       (_
973        (let* ((end (max lurk-input-marker (point)))
974               (space-idx (save-excursion
975                            (re-search-backward " " lurk-input-marker t)))
976               (start (if space-idx (+ 1 space-idx) lurk-input-marker))
977               (completion-ignore-case t))
978          (unless (string-prefix-p "/" (buffer-substring start end))
979            (completion-in-region start end (lurk-get-context-users lurk-current-context))))))))
980
981
982 ;;; Mode
983 ;;
984
985 (defvar lurk-mode-map
986   (let ((map (make-sparse-keymap)))
987     (define-key map (kbd "RET") 'lurk-enter)
988     (define-key map (kbd "<tab>") 'lurk-complete-input)
989     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
990     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
991     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
992     (define-key map (kbd "<C-up>") 'lurk-history-prev)
993     (define-key map (kbd "<C-down>") 'lurk-history-next)
994     ;; (when (fboundp 'evil-define-key*)
995     ;;   (evil-define-key* 'insert map
996     ;;                     (kbd "<C-Up>") 'lurk-history-prev
997     ;;                     (kbd "<C-Down>") 'lurk-history-next))
998     map))
999
1000 (defvar lurk-mode-map)
1001
1002 (define-derived-mode lurk-mode text-mode "lurk"
1003   "Major mode for LURK.")
1004
1005 (when (fboundp 'evil-set-initial-state)
1006   (evil-set-initial-state 'lurk-mode 'insert))
1007
1008 ;;; Main start procedure
1009 ;;
1010
1011 (defun lurk ()
1012   "Switch to *lurk* buffer."
1013   (interactive)
1014   (if (get-buffer "*lurk*")
1015       (switch-to-buffer "*lurk*")
1016     (switch-to-buffer "*lurk*")
1017     (lurk-mode)
1018     (lurk-setup-buffer))
1019   "Started LURK.")
1020
1021
1022 ;;; lurk.el ends here