Made command completion extensible.
[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
813 ;;; Commands
814 ;;
815
816 (defvar lurk-command-table
817   '(("DEBUG" "Toggle debug mode on/off." lurk-command-debug lurk-boolean-completions)
818     ("HEADER" "Toggle display of header." lurk-command-header lurk-boolean-completions)
819     ("CONNECT" "Connect to an IRC network." lurk-command-connect lurk-network-completions)
820     ("TOPIC" "Set topic for current channel." lurk-command-topic)
821     ("ME" "Display action." lurk-command-me)
822     ("VERSION" "Request version of another user's client via CTCP." lurk-command-version)
823     ("PART" "Leave channel." lurk-command-part lurk-context-completions)
824     ("QUIT" "Disconnect from current network." lurk-command-quit)
825     ("NICK" "Change nick." lurk-command-nick)
826     ("LIST" "Display details of one or more channels." lurk-command-list)
827     ("MSG" "Send private message to user." lurk-command-msg lurk-nick-completions))
828   "Table of commands explicitly supported by Lurk.")
829
830 (defun lurk-boolean-completions ()
831   '("on" "off"))
832
833 (defun lurk-network-completions ()
834   (mapcar (lambda (row) (car row)) lurk-networks))
835
836 (defun lurk-nick-completions ()
837   (lurk-get-context-users lurk-current-context))
838
839 (defun lurk-context-completions ()
840   (lurk-get-context-list))
841
842
843 ;;; Command entering
844 ;;
845
846 (defun lurk-enter-string (string)
847   (if (string-prefix-p "/" string)
848       (pcase string
849         ((rx (: "/" (let cmd-str (+ (not whitespace)))
850                 (opt (+ whitespace)
851                      (let params-str (+ anychar))
852                      string-end)))
853          (let ((command-row (assoc (upcase  cmd-str) lurk-command-table #'equal))
854                (params (if params-str
855                            (split-string params-str nil t)
856                          nil)))
857            (if command-row
858                (funcall (elt command-row 2) params)
859              (lurk-send-msg (lurk-msg nil nil (upcase cmd-str) params)))))
860         (_
861          (lurk-display-error "Badly formed command.")))
862     (unless (string-empty-p string)
863       (if lurk-current-context
864           (progn
865             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
866                                      lurk-current-context
867                                      string))
868             (lurk-display-message lurk-nick lurk-current-context string))
869         (lurk-display-error "No current context.")))))
870
871 (defun lurk-command-debug (params)
872   (setq lurk-debug 
873         (if params
874             (if (equal (upcase (car params)) "ON")
875                 t
876               nil)
877           (not lurk-debug)))
878   (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
879
880 (defun lurk-command-header (params)
881   (if
882       (if params
883           (equal (upcase (car params)) "ON")
884         (not header-line-format))
885       (progn
886         (lurk-setup-header)
887         (lurk-display-notice nil "Header enabled."))
888     (setq-local header-line-format nil)
889     (lurk-display-notice nil "Header disabled.")))
890
891 (defun lurk-command-connect (params)
892   (if params
893       (let ((network (car params)))
894         (lurk-display-notice nil "Attempting to connect to " network "...")
895         (lurk-connect network))
896     (lurk-display-notice nil "Usage: /connect <network>")))
897
898 (defun lurk-command-quit (params)
899   (let ((quit-msg (if params (string-join params " ") nil)))
900     (lurk-send-msg (lurk-msg nil nil "QUIT" quit-msg))))
901
902 (defun lurk-command-part (params)
903   (let ((channel (if params (car params) lurk-current-context)))
904     (if channel
905         (lurk-send-msg (lurk-msg nil nil "PART" channel))
906       (lurk-display-error "No current channel to leave."))))
907
908 (defun lurk-command-version (params)
909   (if params
910       (let ((nick (car params)))
911         (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
912                                  (list nick "\01VERSION\01")))
913         (lurk-display-notice nil "CTCP version request sent to " nick))
914     (lurk-display-notice nil "Usage: /version <nick>")))
915
916 (defun lurk-command-quit (params)
917   (let ((quit-msg (if params (string-join parms " ") lurk-default-quit-msg)))
918     (lurk-send-msg (lurk-msg nil nil "QUIT" quit-msg))))
919
920 (defun lurk-command-nick (params)
921   (let ((new-nick (if params (string-join params " ") nil)))
922     (if new-nick
923         (if (lurk-connected-p)
924             (lurk-send-msg (lurk-msg nil nil "NICK" new-nick))
925           (setq lurk-nick nick)
926           (lurk-display-notice nil "Set default nick to '" nick "'."))
927       (lurk-display-notice nil "Current nick: " lurk-nick))))
928
929 (defun lurk-command-me (params)
930   (if lurk-current-context
931       (if params
932           (let* ((action (string-join params " "))
933                  (ctcp-text (concat "\01ACTION " action "\01")))
934             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
935                                      (list lurk-current-context ctcp-text)))
936             (lurk-display-action lurk-nick lurk-current-context action))
937         (lurk-display-notice nil "Usage: /me <action>"))
938     (lurk-display-notice nil "No current channel.")))
939
940 (defun lurk-command-list (params)
941   (if (not params)
942       (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.")
943     (if (equal (upcase (car params)) "-YES")
944         (lurk-send-msg (lurk-msg nil nil "LIST"))
945       (lurk-send-msg (lurk-msg nil nil "LIST" (car params))))))
946
947 (defun lurk-command-topic (params)
948   (if lurk-current-context
949       (if params
950           (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context (string-join params " ")))
951         (lurk-display-notice nil "Usage: /topic <new topic>"))
952     (lurk-display-notice nil "No current channel.")))
953
954 (defun lurk-command-msg (params)
955   (if (and params (>= 2 (length params)))
956       (let ((to (car params))
957             (text (string-join (cdr params) " ")))
958         (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
959         (lurk-display-message lurk-nick to text))
960     (lurk-display-notice nil "Usage: /msg <nick> <message>")))
961
962
963 ;;; Command history
964 ;;
965
966 (defvar lurk-history nil
967   "Commands and messages sent in current session.")
968
969
970 (defun lurk-enter ()
971   "Enter current contents of line after prompt."
972   (interactive)
973   (with-current-buffer "*lurk*"
974     (let ((line (buffer-substring lurk-input-marker (point-max))))
975       (push line lurk-history)
976       (setq lurk-history-index nil)
977       (let ((inhibit-read-only t))
978         (delete-region lurk-input-marker (point-max)))
979       (lurk-enter-string line))))
980
981 (defvar lurk-history-index nil)
982
983 (defun lurk-history-cycle (delta)
984   (when lurk-history
985     (with-current-buffer "*lurk*"
986       (if lurk-history-index
987           (setq lurk-history-index
988                 (max 0
989                      (min (- (length lurk-history) 1)
990                           (+ delta lurk-history-index))))
991         (setq lurk-history-index 0))
992       (delete-region lurk-input-marker (point-max))
993       (insert (elt lurk-history lurk-history-index)))))
994
995 (defun lurk-history-next ()
996   (interactive)
997   (lurk-history-cycle -1))
998
999 (defun lurk-history-prev ()
1000   (interactive)
1001   (lurk-history-cycle +1))
1002
1003
1004 ;;; Interactive functions
1005 ;;
1006
1007 (defun lurk-cycle-contexts-forward ()
1008   (interactive)
1009   (lurk-cycle-contexts))
1010
1011 (defun lurk-cycle-contexts-reverse ()
1012   (interactive)
1013   (lurk-cycle-contexts t))
1014
1015 (defvar lurk-zoomed nil
1016   "Keeps track of zoom status.")
1017
1018 (defun lurk-toggle-zoom ()
1019   (interactive)
1020   (if lurk-zoomed
1021       (lurk-zoom-out)
1022     (lurk-zoom-in lurk-current-context))
1023   (setq lurk-zoomed (not lurk-zoomed)))
1024
1025 (defun lurk-complete-input ()
1026   (interactive)
1027   (let ((completion-ignore-case t))
1028     (when (and (>= (point) lurk-input-marker))
1029       (pcase (buffer-substring lurk-input-marker (point))
1030         ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
1031          (let ((space-idx (save-excursion
1032                             (re-search-backward " " lurk-input-marker t)))
1033                (table-row (assoc (upcase cmd-str) lurk-command-table #'equal)))
1034            (if (and table-row (elt table-row 3))
1035                (let ((completions (funcall (elt table-row 3))))
1036                  (completion-in-region (+ 1 space-idx) (point) completions)))))
1037         ((rx (: "/" (* (not whitespace)) string-end))
1038          (message (buffer-substring lurk-input-marker (point)))
1039          (completion-in-region lurk-input-marker (point)
1040                                (mapcar (lambda (row) (string-join (list "/" (car row))))
1041                                        lurk-command-table)))
1042         (_
1043          (let* ((end (max lurk-input-marker (point)))
1044                 (space-idx (save-excursion
1045                              (re-search-backward " " lurk-input-marker t)))
1046                 (start (if space-idx (+ 1 space-idx) lurk-input-marker)))
1047            (unless (string-prefix-p "/" (buffer-substring start end))
1048              (completion-in-region start end (lurk-get-context-users lurk-current-context)))))))))
1049
1050
1051 ;;; Mode
1052 ;;
1053
1054 (defvar lurk-mode-map
1055   (let ((map (make-sparse-keymap)))
1056     (define-key map (kbd "RET") 'lurk-enter)
1057     (define-key map (kbd "<tab>") 'lurk-complete-input)
1058     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
1059     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
1060     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
1061     (define-key map (kbd "<C-up>") 'lurk-history-prev)
1062     (define-key map (kbd "<C-down>") 'lurk-history-next)
1063     map))
1064
1065 (defvar lurk-mode-map)
1066
1067 (define-derived-mode lurk-mode text-mode "lurk"
1068   "Major mode for LURK.")
1069
1070 (when (fboundp 'evil-set-initial-state)
1071   (evil-set-initial-state 'lurk-mode 'insert))
1072
1073 ;;; Main start procedure
1074 ;;
1075
1076 (defun lurk ()
1077   "Switch to *lurk* buffer."
1078   (interactive)
1079   (if (get-buffer "*lurk*")
1080       (switch-to-buffer "*lurk*")
1081     (switch-to-buffer "*lurk*")
1082     (lurk-mode)
1083     (lurk-setup-buffer))
1084   "Started LURK.")
1085
1086
1087 ;;; lurk.el ends here