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