Appended spaces to autocompletions.
[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 (or (any "\x02\x1D\x1F\x1E\x0F")
584                                         (: "\x03" (+ digit) (opt "," (* digit))))) nil t)
585         (let ((beg (+ (match-beginning 0) 1)))
586           (if bold
587               (add-face-text-property prev-point beg '(:weight bold)))
588           (if italics
589               (add-face-text-property prev-point beg '(:slant italic)))
590           (if underline
591               (add-face-text-property prev-point beg '(:underline t)))
592           (if strikethrough
593               (add-face-text-property prev-point beg '(:strike-through t)))
594           (pcase (match-string 0)
595             ("\x02" (setq bold (not bold)))
596             ("\x1D" (setq italics (not italics)))
597             ("\x1F" (setq underline (not underline)))
598             ("\x1E" (setq strikethrough (not strikethrough)))
599             ("\x0F" ; Reset
600              (setq bold nil)
601              (setq italics nil)
602              (setq underline nil)
603              (setq strikethrough nil))
604             (_))
605           (delete-region (match-beginning 0) (match-end 0))
606           (setq prev-point (point)))))
607     (buffer-string)))
608
609
610 ;;; Message evaluation
611 ;;
612
613 (defun lurk-eval-msg-string (string)
614   (if lurk-debug
615       (lurk-display-string nil nil string))
616   (let* ((msg (lurk-string->msg string)))
617     (lurk-process-autoreplies msg)
618     (pcase (lurk-msg-cmd msg)
619       ("PING"
620        (lurk-send-msg
621         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
622
623       ("PONG")
624
625       ("001"
626        (let* ((params (lurk-msg-params msg))
627               (nick (elt params 0))
628               (text (string-join (seq-drop params 1) " ")))
629          (setq lurk-nick nick)
630          (lurk-display-notice nil text)))
631
632       ("353" ; NAMEREPLY
633        (let* ((params (lurk-msg-params msg))
634               (channel (elt params 2))
635               (names (split-string (elt params 3))))
636          (lurk-add-context-users channel names)))
637
638       ("366" ; ENDOFNAMES
639        (let* ((params (lurk-msg-params msg))
640               (channel (elt params 1)))
641          (lurk-display-notice
642           channel
643           (lurk--as-string (length (lurk-get-context-users channel)))
644           " users in " channel)))
645
646       ("331"
647        (let* ((params (lurk-msg-params msg))
648               (channel (elt params 1)))
649          (lurk-display-notice
650           channel
651           "No topic set.")))
652
653       ("332"
654        (let* ((params (lurk-msg-params msg))
655               (channel (elt params 1))
656               (topic (elt params 2)))
657          (lurk-display-notice channel "Topic: " topic)))
658
659       ("333") ; Avoid displaying these
660
661       ((rx (= 3 (any digit)))
662        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
663
664       ((and "JOIN"
665             (guard (equal lurk-nick (lurk-msg-src msg))))
666        (let ((channel (car (lurk-msg-params msg))))
667          (lurk-add-context channel)
668          (lurk-set-current-context channel)
669          (lurk-display-notice channel "Joining channel " channel)
670          (lurk-render-prompt)))
671
672       ("JOIN"
673        (let ((channel (car (lurk-msg-params msg)))
674              (nick (lurk-msg-src msg)))
675          (lurk-add-context-users channel (list nick))
676          (if lurk-show-joins
677              (lurk-display-notice channel nick " joined channel " channel))))
678
679       ((and "PART"
680             (guard (equal lurk-nick (lurk-msg-src msg))))
681        (let ((channel (car (lurk-msg-params msg))))
682          (lurk-display-notice channel "Left channel " channel)
683          (lurk-del-context channel)
684          (if (equal channel lurk-current-context)
685              (lurk-set-current-context (lurk-get-next-context)))
686          (lurk-render-prompt)))
687
688       ("PART"
689        (let ((channel (car (lurk-msg-params msg)))
690              (nick (lurk-msg-src msg)))
691          (lurk-del-context-user channel nick)
692          (if lurk-show-joins
693              (lurk-display-notice channel nick " left channel " channel))))
694
695       ((and "KICK")
696        (let ((kicker-nick (lurk-msg-src msg))
697              (channel (car (lurk-msg-params msg)))
698              (nick (cadr (lurk-msg-params msg)))
699              (reason (caddr (lurk-msg-params msg))))
700          (if (equal nick lurk-nick)
701              (progn
702                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
703                (lurk-del-context channel)
704                (if (equal channel lurk-current-context)
705                    (lurk-set-current-context (lurk-get-next-context)))
706                (lurk-render-prompt))
707            (lurk-del-context-user channel nick)
708            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
709
710       ("QUIT"
711        (let ((nick (lurk-msg-src msg))
712              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
713          (lurk-del-user nick)
714          (if lurk-show-joins
715              (lurk-display-notice nil nick " quit: " reason))))
716
717       ((and "NICK"
718             (guard (equal lurk-nick (lurk-msg-src msg))))
719        (setq lurk-nick (car (lurk-msg-params msg)))
720        (lurk-display-notice nil "Set nick to " lurk-nick))
721
722       ("NICK"
723        (let ((old-nick (lurk-msg-src msg))
724              (new-nick (car (lurk-msg-params msg))))
725          (lurk-display-notice nil old-nick " is now known as " new-nick)
726          (lurk-rename-user old-nick new-nick)))
727
728       ("NOTICE"
729        (let ((nick (lurk-msg-src msg))
730              (channel (car (lurk-msg-params msg)))
731              (text (cadr (lurk-msg-params msg))))
732          (pcase text
733            ((rx (: "\01VERSION "
734                    (let version (* (not "\01")))
735                    "\01"))
736             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
737            (_
738             (lurk-display-notice nil text)))))
739
740       ("PRIVMSG"
741        (let* ((from (lurk-msg-src msg))
742               (params (lurk-msg-params msg))
743               (to (car params))
744               (text (cadr params)))
745          (pcase text
746            ("\01VERSION\01"
747             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
748               (lurk-send-msg (lurk-msg nil nil "NOTICE"
749                                        (list from (concat "\01VERSION "
750                                                           version-string
751                                                           "\01")))))
752             (lurk-display-notice nil "CTCP version request received from " from))
753
754            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
755             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
756             (lurk-display-notice from "CTCP ping received from " from))
757
758            ("\01USERINFO\01"
759             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
760
761            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
762             (lurk-display-action from to action-text))
763
764            (_
765             (lurk-display-message from to text)))))
766       (_
767        (lurk-display-notice nil (lurk-msg->string msg))))))
768
769
770 ;;; User-defined responses
771
772
773 (defvar lurk-autoreply-table nil
774   "Table of autoreply messages.
775
776 Each autoreply is a list of two elements: (matcher reply)
777
778 Here matcher is a list:
779
780 (network src cmd params ...)
781
782 and reply is another list:
783
784  (cmd params ...)
785
786 Each entry in the matcher list is a regular expression tested against the
787 corresponding values in the incomming message.  Entries can be nil,
788 in which case they match anything.")
789
790 (defun lurk--lists-equal (l1 l2)
791     (if (and l1 l2)
792         (if (or (not (and (car l1) (car l2)))
793                 (string-match (car l1) (car l2)))
794             (lurk--lists-equal (cdr l1) (cdr l2))
795           nil)
796       t))
797
798 (defun lurk-process-autoreply (msg autoreply)
799   (let ((matcher (car autoreply))
800         (reply (cadr autoreply)))
801     (let ((network (car matcher)))
802       (when (and (or (not network)
803                      (and (get-process "lurk")
804                           (equal (car (process-contact (get-process "lurk")))
805                                  (cadr (assoc network lurk-networks)))))
806                  (lurk--lists-equal (cdr matcher)
807                                     (append (list (lurk-msg-src msg)
808                                                   (lurk-msg-cmd msg))
809                                             (lurk-msg-params msg))))
810         (lurk-send-msg
811          (lurk-msg nil nil (car reply) (cdr reply)))))))
812
813 (defun lurk-process-autoreplies (msg)
814   (mapc
815    (lambda (autoreply)
816      (lurk-process-autoreply msg autoreply))
817    lurk-autoreply-table))
818
819
820 ;;; Commands
821 ;;
822
823 (defvar lurk-command-table
824   '(("DEBUG" "Toggle debug mode on/off." lurk-command-debug lurk-boolean-completions)
825     ("HEADER" "Toggle display of header." lurk-command-header lurk-boolean-completions)
826     ("CONNECT" "Connect to an IRC network." lurk-command-connect lurk-network-completions)
827     ("TOPIC" "Set topic for current channel." lurk-command-topic)
828     ("ME" "Display action." lurk-command-me)
829     ("VERSION" "Request version of another user's client via CTCP." lurk-command-version)
830     ("PART" "Leave channel." lurk-command-part lurk-context-completions)
831     ("QUIT" "Disconnect from current network." lurk-command-quit)
832     ("NICK" "Change nick." lurk-command-nick)
833     ("LIST" "Display details of one or more channels." lurk-command-list)
834     ("MSG" "Send private message to user." lurk-command-msg lurk-nick-completions)
835     ("HELP" "Display help on client commands." lurk-command-help lurk-help-completions))
836   "Table of commands explicitly supported by Lurk.")
837
838 (defun lurk-boolean-completions ()
839   '("on" "off"))
840
841 (defun lurk-network-completions ()
842   (mapcar (lambda (row) (car row)) lurk-networks))
843
844 (defun lurk-nick-completions ()
845   (lurk-get-context-users lurk-current-context))
846
847 (defun lurk-context-completions ()
848   (lurk-get-context-list))
849
850 (defun lurk-help-completions ()
851   (mapcar (lambda (row) (car row)) lurk-command-table))
852
853 (defun lurk-command-help (params)
854   (if params
855       (let* ((cmd-str (upcase (car params)))
856              (row (assoc cmd-str lurk-command-table #'equal)))
857         (if row
858             (progn
859               (lurk-display-notice nil "Help for \x02" cmd-str "\x02:")
860               (lurk-display-notice nil "  " (elt row 1)))
861           (lurk-display-notice nil "No such (client-interpreted) command.")))
862     (lurk-display-notice nil "Client-interpreted commands:")
863     (dolist (row lurk-command-table)
864       (lurk-display-notice nil "  \x02" (elt row 0) "\x02: " (elt row 1)))
865     (lurk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
866
867 ;;; Command entering
868 ;;
869
870 (defun lurk-enter-string (string)
871   (if (string-prefix-p "/" string)
872       (pcase string
873         ((rx (: "/" (let cmd-str (+ (not whitespace)))
874                 (opt (+ whitespace)
875                      (let params-str (+ anychar))
876                      string-end)))
877          (let ((command-row (assoc (upcase  cmd-str) lurk-command-table #'equal))
878                (params (if params-str
879                            (split-string params-str nil t)
880                          nil)))
881            (if command-row
882                (funcall (elt command-row 2) params)
883              (lurk-send-msg (lurk-msg nil nil (upcase cmd-str) params)))))
884         (_
885          (lurk-display-error "Badly formed command.")))
886     (unless (string-empty-p string)
887       (if lurk-current-context
888           (progn
889             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
890                                      lurk-current-context
891                                      string))
892             (lurk-display-message lurk-nick lurk-current-context string))
893         (lurk-display-error "No current context.")))))
894
895 (defun lurk-command-debug (params)
896   (setq lurk-debug 
897         (if params
898             (if (equal (upcase (car params)) "ON")
899                 t
900               nil)
901           (not lurk-debug)))
902   (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
903
904 (defun lurk-command-header (params)
905   (if
906       (if params
907           (equal (upcase (car params)) "ON")
908         (not header-line-format))
909       (progn
910         (lurk-setup-header)
911         (lurk-display-notice nil "Header enabled."))
912     (setq-local header-line-format nil)
913     (lurk-display-notice nil "Header disabled.")))
914
915 (defun lurk-command-connect (params)
916   (if params
917       (let ((network (car params)))
918         (lurk-display-notice nil "Attempting to connect to " network "...")
919         (lurk-connect network))
920     (lurk-display-notice nil "Usage: /connect <network>")))
921
922 (defun lurk-command-quit (params)
923   (let ((quit-msg (if params (string-join params " ") nil)))
924     (lurk-send-msg (lurk-msg nil nil "QUIT" quit-msg))))
925
926 (defun lurk-command-part (params)
927   (let ((channel (if params (car params) lurk-current-context)))
928     (if channel
929         (lurk-send-msg (lurk-msg nil nil "PART" channel))
930       (lurk-display-error "No current channel to leave."))))
931
932 (defun lurk-command-version (params)
933   (if params
934       (let ((nick (car params)))
935         (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
936                                  (list nick "\01VERSION\01")))
937         (lurk-display-notice nil "CTCP version request sent to " nick))
938     (lurk-display-notice nil "Usage: /version <nick>")))
939
940 (defun lurk-command-quit (params)
941   (let ((quit-msg (if params (string-join parms " ") lurk-default-quit-msg)))
942     (lurk-send-msg (lurk-msg nil nil "QUIT" quit-msg))))
943
944 (defun lurk-command-nick (params)
945   (let ((new-nick (if params (string-join params " ") nil)))
946     (if new-nick
947         (if (lurk-connected-p)
948             (lurk-send-msg (lurk-msg nil nil "NICK" new-nick))
949           (setq lurk-nick nick)
950           (lurk-display-notice nil "Set default nick to '" nick "'."))
951       (lurk-display-notice nil "Current nick: " lurk-nick))))
952
953 (defun lurk-command-me (params)
954   (if lurk-current-context
955       (if params
956           (let* ((action (string-join params " "))
957                  (ctcp-text (concat "\01ACTION " action "\01")))
958             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
959                                      (list lurk-current-context ctcp-text)))
960             (lurk-display-action lurk-nick lurk-current-context action))
961         (lurk-display-notice nil "Usage: /me <action>"))
962     (lurk-display-notice nil "No current channel.")))
963
964 (defun lurk-command-list (params)
965   (if (not params)
966       (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.")
967     (if (equal (upcase (car params)) "-YES")
968         (lurk-send-msg (lurk-msg nil nil "LIST"))
969       (lurk-send-msg (lurk-msg nil nil "LIST" (car params))))))
970
971 (defun lurk-command-topic (params)
972   (if lurk-current-context
973       (if params
974           (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context (string-join params " ")))
975         (lurk-display-notice nil "Usage: /topic <new topic>"))
976     (lurk-display-notice nil "No current channel.")))
977
978 (defun lurk-command-msg (params)
979   (if (and params (>= 2 (length params)))
980       (let ((to (car params))
981             (text (string-join (cdr params) " ")))
982         (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
983         (lurk-display-message lurk-nick to text))
984     (lurk-display-notice nil "Usage: /msg <nick> <message>")))
985
986
987 ;;; Command history
988 ;;
989
990 (defvar lurk-history nil
991   "Commands and messages sent in current session.")
992
993
994 (defun lurk-enter ()
995   "Enter current contents of line after prompt."
996   (interactive)
997   (with-current-buffer "*lurk*"
998     (let ((line (buffer-substring lurk-input-marker (point-max))))
999       (push line lurk-history)
1000       (setq lurk-history-index nil)
1001       (let ((inhibit-read-only t))
1002         (delete-region lurk-input-marker (point-max)))
1003       (lurk-enter-string line))))
1004
1005 (defvar lurk-history-index nil)
1006
1007 (defun lurk-history-cycle (delta)
1008   (when lurk-history
1009     (with-current-buffer "*lurk*"
1010       (if lurk-history-index
1011           (setq lurk-history-index
1012                 (max 0
1013                      (min (- (length lurk-history) 1)
1014                           (+ delta lurk-history-index))))
1015         (setq lurk-history-index 0))
1016       (delete-region lurk-input-marker (point-max))
1017       (insert (elt lurk-history lurk-history-index)))))
1018
1019 (defun lurk-history-next ()
1020   (interactive)
1021   (lurk-history-cycle -1))
1022
1023 (defun lurk-history-prev ()
1024   (interactive)
1025   (lurk-history-cycle +1))
1026
1027
1028 ;;; Interactive functions
1029 ;;
1030
1031 (defun lurk-cycle-contexts-forward ()
1032   (interactive)
1033   (lurk-cycle-contexts))
1034
1035 (defun lurk-cycle-contexts-reverse ()
1036   (interactive)
1037   (lurk-cycle-contexts t))
1038
1039 (defvar lurk-zoomed nil
1040   "Keeps track of zoom status.")
1041
1042 (defun lurk-toggle-zoom ()
1043   (interactive)
1044   (if lurk-zoomed
1045       (lurk-zoom-out)
1046     (lurk-zoom-in lurk-current-context))
1047   (setq lurk-zoomed (not lurk-zoomed)))
1048
1049 (defun lurk-complete-input ()
1050   (interactive)
1051   (let ((completion-ignore-case t))
1052     (when (and (>= (point) lurk-input-marker))
1053       (pcase (buffer-substring lurk-input-marker (point))
1054         ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
1055          (let ((space-idx (save-excursion
1056                             (re-search-backward " " lurk-input-marker t)))
1057                (table-row (assoc (upcase cmd-str) lurk-command-table #'equal)))
1058            (if (and table-row (elt table-row 3))
1059                (let* ((completions-nospace (funcall (elt table-row 3)))
1060                       (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
1061                  (completion-in-region (+ 1 space-idx) (point) completions)))))
1062         ((rx (: "/" (* (not whitespace)) string-end))
1063          (message (buffer-substring lurk-input-marker (point)))
1064          (completion-in-region lurk-input-marker (point)
1065                                (mapcar (lambda (row) (concat "/" (car row) " "))
1066                                        lurk-command-table)))
1067         (_
1068          (let* ((end (max lurk-input-marker (point)))
1069                 (space-idx (save-excursion
1070                              (re-search-backward " " lurk-input-marker t)))
1071                 (start (if space-idx (+ 1 space-idx) lurk-input-marker)))
1072            (unless (string-prefix-p "/" (buffer-substring start end))
1073              (completion-in-region start end (lurk-get-context-users lurk-current-context)))))))))
1074
1075
1076 ;;; Mode
1077 ;;
1078
1079 (defvar lurk-mode-map
1080   (let ((map (make-sparse-keymap)))
1081     (define-key map (kbd "RET") 'lurk-enter)
1082     (define-key map (kbd "<tab>") 'lurk-complete-input)
1083     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
1084     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
1085     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
1086     (define-key map (kbd "<C-up>") 'lurk-history-prev)
1087     (define-key map (kbd "<C-down>") 'lurk-history-next)
1088     map))
1089
1090 (defvar lurk-mode-map)
1091
1092 (define-derived-mode lurk-mode text-mode "lurk"
1093   "Major mode for LURK.")
1094
1095 (when (fboundp 'evil-set-initial-state)
1096   (evil-set-initial-state 'lurk-mode 'insert))
1097
1098 ;;; Main start procedure
1099 ;;
1100
1101 (defun lurk ()
1102   "Switch to *lurk* buffer."
1103   (interactive)
1104   (if (get-buffer "*lurk*")
1105       (switch-to-buffer "*lurk*")
1106     (switch-to-buffer "*lurk*")
1107     (lurk-mode)
1108     (lurk-setup-buffer))
1109   "Started LURK.")
1110
1111
1112 ;;; lurk.el ends here