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