Fixed list command.
[lurk.git] / lurk.el
1 ;;; lurk.el --- Little Uni-buffer 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 Uni-buffer 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     ("freenode" "chat.freenode.net" 6697)
50     ("tilde" "tilde.chat" 6697)
51     ("mbr" "mbrserver.com" 6667 :notls)
52     ("local" "localhost" 6697))
53   "IRC networks.")
54
55 (defcustom lurk-allow-ipv6 nil
56   "Set to non-nil to allow use of IPv6.")
57
58 (defcustom lurk-show-joins nil
59   "Set to non-nil to be notified of joins, parts and quits.")
60
61 (defcustom lurk-display-header t
62   "If non-nil, use buffer header to display information on current host and channel.")
63
64 ;;; Faces
65 ;;
66
67 (defface lurk-text
68   '((t :inherit default))
69   "Face used for Lurk text.")
70
71 (defface lurk-prompt
72   '((t :inherit org-priority))
73   "Face used for the prompt.")
74
75 (defface lurk-context
76   '((t :inherit org-tag))
77   "Face used for the context name in the prompt.")
78
79 (defface lurk-faded
80   '((t :inherit org-agenda-dimmed-todo-face))
81   "Face used for faded Lurk text.")
82
83 (defface lurk-timestamp
84   '((t :inherit org-agenda-dimmed-todo-face))
85   "Face used for timestamps.")
86
87 (defface lurk-error
88   '((t :inherit font-lock-regexp-grouping-construct))
89   "Face used for Lurk error text.")
90
91 (defface lurk-notice
92   '((t :inherit org-upcoming-deadline))
93   "Face used for Lurk notice text.")
94
95 ;;; Global variables
96 ;;
97
98 (defvar lurk-version "Lurk v0.1"
99   "Value of this string is used in response to CTCP version queries.")
100
101 (defvar lurk-notice-prefix "-!-")
102
103 (defvar lurk-error-prefix "!!!")
104
105 (defvar lurk-prompt-string ">")
106
107 (defvar lurk-debug nil
108   "If non-nil, enable debug mode.")
109
110 ;;; Network process
111 ;;
112
113 (defvar lurk-response "")
114
115 (defun lurk-filter (proc string)
116   (dolist (line (split-string (concat lurk-response string) "\n"))
117     (if (string-suffix-p "\r" line)
118         (lurk-eval-msg-string (string-trim line))
119       (setq lurk-response line))))
120
121 (defun lurk-sentinel (proc string)
122   (unless (equal "open" (string-trim string))
123     (lurk-display-error "Disconnected from server.")
124     (clrhash lurk-contexts)
125     (lurk-set-current-context nil)
126     (lurk-render-prompt)
127     (cancel-timer lurk-ping-timer)))
128
129 (defun lurk-start-process (network)
130   (let* ((row (assoc network lurk-networks))
131          (host (elt row 1))
132          (port (elt row 2))
133          (flags (seq-drop row 3)))
134     (make-network-process :name "lurk"
135                           :host host
136                           :service port
137                           :family (if lurk-allow-ipv6 nil 'ipv4)
138                           :filter #'lurk-filter
139                           :sentinel #'lurk-sentinel
140                           :nowait nil
141                           :tls-parameters (if (memq :notls flags)
142                                               nil
143                                             (cons 'gnutls-x509pki
144                                                   (gnutls-boot-parameters
145                                                    :type 'gnutls-x509pki
146                                                    :hostname host)))
147                           :buffer "*lurk*")))
148
149 (defvar lurk-ping-timer nil)
150 (defvar lurk-ping-period 60)
151
152 (defun lurk-ping-function ()
153   (lurk-send-msg (lurk-msg nil nil "PING" (car (process-contact (get-process "lurk")))))
154   (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))
155
156 (defun lurk-connect (network)
157   (if (get-process "lurk")
158       (lurk-display-error "Already connected.  Disconnect first.")
159     (if (not (assoc network lurk-networks))
160         (lurk-display-error "Network '" network "' is unknown.")
161       (clrhash lurk-contexts)
162       (lurk-set-current-context nil)
163       (lurk-start-process network)
164       (lurk-send-msg (lurk-msg nil nil "USER" lurk-nick 0 "*" lurk-nick))
165       (lurk-send-msg (lurk-msg nil nil "NICK" lurk-nick))
166       (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))))
167
168 (defun lurk-connected-p ()
169   (let ((proc (get-process "lurk")))
170     (and proc (eq (process-status proc) 'open))))
171
172 (defun lurk-send-msg (msg)
173   (if lurk-debug
174       (lurk-display-string nil nil (lurk-msg->string msg)))
175   (let ((proc (get-process "lurk")))
176     (if (and proc (eq (process-status proc) 'open))
177         (process-send-string proc (concat (lurk-msg->string msg) "\r\n"))
178       (lurk-display-error "No server connection established.")
179       (error "No server connection established"))))
180
181
182 ;;; Server messages
183 ;;
184
185 (defun lurk--as-string (obj)
186   (if obj
187       (with-output-to-string (princ obj))
188     nil))
189
190 (defun lurk-msg (tags src cmd &rest params)
191   (list (lurk--as-string tags)
192         (lurk--as-string src)
193         (upcase (lurk--as-string cmd))
194         (mapcar #'lurk--as-string
195                 (if (and params (listp (elt params 0)))
196                     (elt params 0)
197                   params))))
198
199 (defun lurk-msg-tags (msg) (elt msg 0))
200 (defun lurk-msg-src (msg) (elt msg 1))
201 (defun lurk-msg-cmd (msg) (elt msg 2))
202 (defun lurk-msg-params (msg) (elt msg 3))
203 (defun lurk-msg-trail (msg)
204   (let ((params (lurk-msg-params msg)))
205     (if params
206         (elt params (- (length params) 1)))))
207
208 (defvar lurk-msg-regex
209   (rx
210    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
211         (* whitespace))
212    (opt (: ":" (: (group (* (not (any space "!" "@"))))
213                   (* (not (any space)))))
214         (* whitespace))
215    (group (: (* (not whitespace))))
216    (* whitespace)
217    (opt (group (+ not-newline))))
218   "Regex used to parse IRC messages.
219 Note that this regex is incomplete.  Noteably, we discard the non-nick
220 portion of the source component of the message, as LURK doesn't use this.")
221
222 (defun lurk-string->msg (string)
223   (if (string-match lurk-msg-regex string)
224       (let* ((tags (match-string 1 string))
225              (src (match-string 2 string))
226              (cmd (upcase (match-string 3 string)))
227              (params-str (match-string 4 string))
228              (params
229               (if params-str
230                   (let* ((idx (cl-search ":" params-str))
231                          (l (split-string (string-trim (substring params-str 0 idx))))
232                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
233                     (append l r))
234                 nil)))
235         (apply #'lurk-msg (append (list tags src cmd) params)))
236     (error "Failed to parse string " string)))
237
238 (defun lurk--filtered-join (&rest args)
239   (string-join (seq-filter (lambda (el) el) args) " "))
240
241 (defun lurk-msg->string (msg)
242   (let ((tags (lurk-msg-tags msg))
243         (src (lurk-msg-src msg))
244         (cmd (lurk-msg-cmd msg))
245         (params (lurk-msg-params msg)))
246     (lurk--filtered-join
247      (if tags (concat "@" tags) nil)
248      (if src (concat ":" src) nil)
249      cmd
250      (if (> (length params) 1)
251          (string-join (seq-take params (- (length params) 1)) " ")
252        nil)
253      (if (> (length params) 0)
254          (concat ":" (elt params (- (length params) 1)))
255        nil))))
256
257
258 ;;; Contexts
259 ;;
260
261 (defvar lurk-current-context nil)
262 (defvar lurk-contexts (make-hash-table :test #'equal))
263
264 (defun lurk-add-context (name)
265   (puthash name nil lurk-contexts))
266
267 (defun lurk-del-context (name)
268   (remhash name lurk-contexts))
269
270 (defun lurk-get-context-users (name)
271   (gethash name lurk-contexts))
272
273 (defun lurk-add-context-users (context users)
274   (puthash context
275            (append users
276                    (gethash context lurk-contexts))
277            lurk-contexts))
278
279 (defun lurk-del-context-user (context user)
280   (puthash context
281            (remove user (gethash context lurk-contexts))
282            lurk-contexts))
283
284 (defun lurk-del-user (user)
285   (dolist (context (lurk-get-context-list))
286     (lurk-del-context-user context user)))
287
288 (defun lurk-rename-user (old-nick new-nick)
289   (dolist (context (lurk-get-context-list))
290     (lurk-del-context-user context old-nick)
291     (lurk-add-context-users context (list new-nick))))
292
293 (defun lurk-get-context-type (name)
294   (cond
295    ((string-prefix-p "#" name) 'channel)
296    ((string-match-p (rx (or "." "localhost")) name) 'host)
297    (t 'nick)))
298
299 (defun lurk-get-context-list ()
300   (let ((res nil))
301     (maphash (lambda (key val)
302                (cl-pushnew key res))
303              lurk-contexts)
304     res))
305
306 (defun lurk-get-next-context (&optional prev)
307   (if lurk-current-context
308       (let* ((context-list (if prev
309                                (reverse (lurk-get-context-list))
310                              (lurk-get-context-list)))
311              (context-list* (member lurk-current-context context-list)))
312         (if (> (length context-list*) 1)
313             (cadr context-list*)
314           (car context-list)))
315     nil))
316
317 (defun lurk-set-current-context (context)
318   (setq lurk-current-context context)
319   (lurk-highlight-context context)
320   (if lurk-zoomed
321       (lurk-zoom-in lurk-current-context)))
322
323 (defun lurk-cycle-contexts (&optional rev)
324   (if lurk-current-context
325       (progn
326         (lurk-set-current-context (lurk-get-next-context rev))
327         (lurk-render-prompt))
328     (lurk-display-error "No channels joined.")))
329
330
331 ;;; Buffer
332 ;;
333
334 (defun lurk-render-prompt ()
335   (with-current-buffer "*lurk*"
336     (let ((update-point (= lurk-input-marker (point)))
337           (update-window-points (mapcar (lambda (w)
338                                           (list (= (window-point w) lurk-input-marker)
339                                                 w))
340                                         (get-buffer-window-list nil nil t))))
341       (save-excursion
342         (set-marker-insertion-type lurk-prompt-marker nil)
343         (set-marker-insertion-type lurk-input-marker t)
344         (let ((inhibit-read-only t))
345           (delete-region lurk-prompt-marker lurk-input-marker)
346           (goto-char lurk-prompt-marker)
347           (insert
348            (propertize (if lurk-current-context
349                            lurk-current-context
350                          "")
351                        'face 'lurk-context
352                        'read-only t)
353            (propertize (concat lurk-prompt-string " ")
354                        'face 'lurk-prompt
355                        'read-only t
356                        'rear-nonsticky t)))
357         (set-marker-insertion-type lurk-input-marker nil))
358       (if update-point
359           (goto-char lurk-input-marker))
360       (dolist (v update-window-points)
361         (if (car v)
362             (set-window-point (cadr v) lurk-input-marker))))))
363   
364 (defvar lurk-prompt-marker nil
365   "Marker for prompt position in LURK buffer.")
366
367 (defvar lurk-input-marker nil
368   "Marker for prompt position in LURK buffer.")
369
370 (defun lurk-setup-header ()
371   (setq-local header-line-format
372               '(:eval
373                 (let ((proc (get-process "lurk")))
374                   (if proc
375                       (concat
376                        "Host: " (car (process-contact proc))
377                        ", Context: "
378                        (if lurk-current-context
379                            (concat
380                             lurk-current-context
381                             " ("
382                             (number-to-string
383                              (length (lurk-get-context-users lurk-current-context)))
384                             " users)")
385                          "Server"))
386                     "No connection")))))
387
388 (defun lurk-setup-buffer ()
389   (with-current-buffer (get-buffer-create "*lurk*")
390     (setq-local scroll-conservatively 1)
391     (setq-local buffer-invisibility-spec nil)
392     (if (markerp lurk-prompt-marker)
393         (set-marker lurk-prompt-marker (point-max))
394       (setq lurk-prompt-marker (point-max-marker)))
395     (if (markerp lurk-input-marker)
396         (set-marker lurk-input-marker (point-max))
397       (setq lurk-input-marker (point-max-marker)))
398     (goto-char (point-max))
399     (lurk-render-prompt)
400     (if lurk-display-header
401         (lurk-setup-header))))
402
403
404 ;;; Output formatting and highlighting
405 ;;
406
407 ;; Partially-implemented idea: the face text property can be
408 ;; a list of faces, applied in order.  By assigning each context
409 ;; a unique list and keeping track of these in a hash table, we can
410 ;; easily switch the face corresponding to a particular context
411 ;; by modifying the elements of this list.
412 ;;
413 ;; More subtly, we make only the cdrs of this list shared among
414 ;; all text of a given context, allowing the cars to be different
415 ;; and for different elements of the context-specific text to have
416 ;; different styling.
417
418 ;; Additionally, we allow selective hiding of contexts via
419 ;; the buffer-invisibility-spec.
420
421 (defvar lurk-context-facelists (make-hash-table :test 'equal)
422   "List of seen contexts and associated face lists.")
423
424 (defun lurk-get-context-facelist (context)
425   (let ((facelist (gethash context lurk-context-facelists)))
426     (unless facelist
427       (setq facelist (list 'lurk-text))
428       (puthash context facelist lurk-context-facelists))
429     facelist))
430
431 (defun lurk--fill-strings (col indent &rest strings)
432   (with-temp-buffer
433     (setq buffer-invisibility-spec nil)
434     (let ((fill-column col)
435           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
436       (apply #'insert strings)
437       (fill-region (point-min) (point-max) nil t)
438       (buffer-string))))
439
440 (defun lurk-display-string (context prefix &rest strings)
441   (with-current-buffer (get-buffer-create "*lurk*")
442     (save-excursion
443       (goto-char lurk-prompt-marker)
444       (let* ((inhibit-read-only t)
445              (old-pos (marker-position lurk-prompt-marker))
446              (padded-timestamp (concat (format-time-string "%H:%M ")))
447              (padded-prefix (if prefix (concat prefix " ") ""))
448              (context-atom (if context (intern context) nil)))
449         (insert-before-markers
450          (lurk--fill-strings
451           80
452           (+ (length padded-timestamp)
453              (length padded-prefix))
454           (propertize padded-timestamp
455                       'face 'lurk-timestamp
456                       'read-only t
457                       'context context
458                       'invisible context-atom)
459           (propertize padded-prefix
460                       'read-only t
461                       'context context
462                       'invisible context-atom)
463           (propertize (concat (lurk-buttonify-urls (apply #'concat strings)) "\n")
464                       'face (lurk-get-context-facelist context)
465                       'read-only t
466                       'context context
467                       'invisible context-atom)))))))
468
469 (defun lurk-display-message (from to text)
470   (let ((context (if (eq 'channel (lurk-get-context-type to))
471                      to
472                    (if (equal to lurk-nick) from to))))
473     (lurk-display-string
474      context
475      (propertize
476       (pcase (lurk-get-context-type to)
477         ('channel (concat to " <" from ">"))
478         ('nick (concat "[" from " -> " to "]"))
479         (_
480          (error "Unsupported context type")))
481       'face (lurk-get-context-facelist context))
482      text)))
483
484 (defun lurk-display-action (from to action-text)
485   (let ((context (if (eq 'channel (lurk-get-context-type to))
486                      to
487                    (if (equal to lurk-nick) from to))))
488     (lurk-display-string
489      context
490      (propertize
491       (concat context " * " from)
492       'face (lurk-get-context-facelist context))
493      action-text)))
494
495 (defun lurk-display-notice (context &rest notices)
496   (lurk-display-string
497    context
498    (propertize lurk-notice-prefix 'face 'lurk-notice)
499    (apply #'concat notices)))
500
501 (defun lurk-display-error (&rest messages)
502   (lurk-display-string
503    nil
504    (propertize lurk-error-prefix 'face 'lurk-error)
505    (apply #'concat messages)))
506
507 (defun lurk-highlight-context (context)
508   (maphash
509    (lambda (this-context facelist)
510      (if (equal this-context context)
511          (setcar facelist 'lurk-text)
512        (setcar facelist 'lurk-faded)))
513    lurk-context-facelists)
514   (force-window-update "*lurk*"))
515
516 (defun lurk-zoom-in (context)
517   (with-current-buffer "*lurk*"
518     (maphash
519      (lambda (this-context _)
520        (when this-context
521          (let ((this-context-atom (intern this-context)))
522            (if (equal this-context context)
523                (remove-from-invisibility-spec this-context-atom)
524              (add-to-invisibility-spec this-context-atom)))))
525      lurk-context-facelists)
526     (force-window-update "*lurk*")))
527
528 (defun lurk-zoom-out ()
529   (with-current-buffer "*lurk*"
530     (maphash
531      (lambda (this-context _)
532        (let ((this-context-atom (if this-context (intern this-context) nil)))
533          (remove-from-invisibility-spec this-context-atom)))
534      lurk-context-facelists)
535     (force-window-update "*lurk*")))
536
537 (defconst lurk-url-regex
538   (rx (:
539        (group (+ alpha))
540        "://"
541        (group (or (+ (any alnum "." "-"))
542                   (+ (any alnum ":"))))
543        (opt (group (: ":" (+ digit))))
544        (opt (group (: "/"
545                       (opt
546                        (* (any alnum "-/.,#:%=&_"))
547                        (any alnum "-/#:%=&_")))))))
548   "Imperfect regex used to find URLs in plain text.")
549
550 (defun lurk-click-url (button)
551   (browse-url (button-get button 'url)))
552
553 (defun lurk-buttonify-urls (string)
554   "Turn substrings which look like urls in STRING into clickable buttons."
555   (with-temp-buffer
556     (insert string)
557     (goto-char (point-min))
558     (while (re-search-forward lurk-url-regex nil t)
559       (let ((url (match-string 0)))
560         (make-text-button (match-beginning 0)
561                           (match-end 0)
562                           'action #'lurk-click-url
563                           'url url
564                           'follow-link t
565                           'face 'button
566                           'help-echo "Open URL in browser.")))
567     (buffer-string)))
568
569
570 ;;; Message evaluation
571 ;;
572
573 (defun lurk-eval-msg-string (string)
574   (if lurk-debug
575       (lurk-display-string nil nil string))
576   (let* ((msg (lurk-string->msg string)))
577     (pcase (lurk-msg-cmd msg)
578       ("PING"
579        (lurk-send-msg
580         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
581
582       ("PONG")
583
584       ("001"
585        (let* ((params (lurk-msg-params msg))
586               (nick (elt params 0))
587               (text (string-join (seq-drop params 1) " ")))
588          (setq lurk-nick nick)
589          (lurk-display-notice nil text)))
590
591       ("353" ; NAMEREPLY
592        (let* ((params (lurk-msg-params msg))
593               (channel (elt params 2))
594               (names (split-string (elt params 3))))
595          (lurk-add-context-users channel names)))
596
597       ("366" ; ENDOFNAMES
598        (let* ((params (lurk-msg-params msg))
599               (channel (elt params 1)))
600          (lurk-display-notice
601           channel
602           (lurk--as-string (length (lurk-get-context-users channel)))
603           " users in " channel)))
604
605       ("331"
606        (let* ((params (lurk-msg-params msg))
607               (channel (elt params 1)))
608          (lurk-display-notice
609           channel
610           "No topic set.")))
611
612       ("332"
613        (let* ((params (lurk-msg-params msg))
614               (channel (elt params 1))
615               (topic (elt params 2)))
616          (lurk-display-notice channel "Topic: " topic)))
617
618       ("333") ; Avoid displaying these
619
620       ((rx (= 3 (any digit)))
621        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
622
623       ((and "JOIN"
624             (guard (equal lurk-nick (lurk-msg-src msg))))
625        (let ((channel (car (lurk-msg-params msg))))
626          (lurk-add-context channel)
627          (lurk-set-current-context channel)
628          (lurk-display-notice channel "Joining channel " channel)
629          (lurk-render-prompt)))
630
631       ("JOIN"
632        (let ((channel (car (lurk-msg-params msg)))
633              (nick (lurk-msg-src msg)))
634          (lurk-add-context-users channel (list nick))
635          (if lurk-show-joins
636              (lurk-display-notice channel nick " joined channel " channel))))
637
638       ((and "PART"
639             (guard (equal lurk-nick (lurk-msg-src msg))))
640        (let ((channel (car (lurk-msg-params msg))))
641          (lurk-display-notice channel "Left channel " channel)
642          (lurk-del-context channel)
643          (if (equal channel lurk-current-context)
644              (lurk-set-current-context (lurk-get-next-context)))
645          (lurk-render-prompt)))
646
647       ("PART"
648        (let ((channel (car (lurk-msg-params msg)))
649              (nick (lurk-msg-src msg)))
650          (lurk-del-context-user channel nick)
651          (if lurk-show-joins
652              (lurk-display-notice channel nick " left channel " channel))))
653
654       ((and "KICK")
655        (let ((kicker-nick (lurk-msg-src msg))
656              (channel (car (lurk-msg-params msg)))
657              (nick (cadr (lurk-msg-params msg)))
658              (reason (caddr (lurk-msg-params msg))))
659          (if (equal nick lurk-nick)
660              (progn
661                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
662                (lurk-del-context channel)
663                (if (equal channel lurk-current-context)
664                    (lurk-set-current-context (lurk-get-next-context)))
665                (lurk-render-prompt))
666            (lurk-del-context-user channel nick)
667            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
668
669       ("QUIT"
670        (let ((nick (lurk-msg-src msg))
671              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
672          (lurk-del-user nick)
673          (if lurk-show-joins
674              (lurk-display-notice nil nick " quit: " reason))))
675
676       ((and "NICK"
677             (guard (equal lurk-nick (lurk-msg-src msg))))
678        (setq lurk-nick (car (lurk-msg-params msg)))
679        (lurk-display-notice nil "Set nick to " lurk-nick))
680
681       ("NICK"
682        (let ((old-nick (lurk-msg-src msg))
683              (new-nick (car (lurk-msg-params msg))))
684          (lurk-display-notice nil old-nick " is now known as " new-nick)
685          (lurk-rename-user old-nick new-nick)))
686
687       ("NOTICE"
688        (let ((nick (lurk-msg-src msg))
689              (channel (car (lurk-msg-params msg)))
690              (text (cadr (lurk-msg-params msg))))
691          (pcase text
692            ((rx (: "\01VERSION "
693                    (let version (* (not "\01")))
694                    "\01"))
695             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
696            (_
697             (lurk-display-notice nil text)))))
698
699       ("PRIVMSG"
700        (let* ((from (lurk-msg-src msg))
701               (params (lurk-msg-params msg))
702               (to (car params))
703               (text (cadr params)))
704          (pcase text
705            ("\01VERSION\01"
706             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
707               (lurk-send-msg (lurk-msg nil nil "NOTICE"
708                                        (list from (concat "\01VERSION "
709                                                           version-string
710                                                           "\01")))))
711             (lurk-display-notice nil "CTCP version request received from " from))
712
713            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
714             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
715             (lurk-display-notice from "CTCP ping received from " from))
716
717            ("\01USERINFO\01"
718             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
719
720            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
721             (lurk-display-action from to action-text))
722
723            (_
724             (lurk-display-message from to text)))))
725       (_
726        (lurk-display-notice nil (lurk-msg->string msg))))))
727
728
729 ;;; Command entering
730 ;;
731
732 (defun lurk-enter-string (string)
733   (if (string-prefix-p "/" string)
734       (pcase (substring string 1)
735         ((rx "DEBUG")
736          (setq lurk-debug (not lurk-debug))
737          (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
738
739         ((rx "HEADER")
740          (if header-line-format
741            (progn
742              (setq-local header-line-format nil)
743              (lurk-display-notice nil "Header disabled."))
744            (lurk-setup-header)
745            (lurk-display-notice nil "Header enabled.")))
746
747         ((rx (: "CONNECT " (let network (* not-newline))))
748          (lurk-display-notice nil "Attempting to connect to " network "...")
749          (lurk-connect network))
750
751         ((rx (: "TOPIC " (let new-topic (* not-newline))))
752          (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context new-topic)))
753
754         ((rx (: "ME " (let action (* not-newline))))
755          (let ((ctcp-text (concat "\01ACTION " action "\01")))
756            (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
757                                     (list lurk-current-context ctcp-text)))
758            (lurk-display-action lurk-nick lurk-current-context action)))
759
760         ((rx (: "VERSION" " " (let nick (+ (not whitespace)))))
761          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
762                                   (list nick "\01VERSION\01")))
763          (lurk-display-notice nil "CTCP version request sent to " nick))
764
765         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
766          (if (or lurk-current-context channel)
767              (lurk-send-msg (lurk-msg nil nil "PART" (if channel
768                                                          channel
769                                                        lurk-current-context)))
770            (lurk-display-error "No current channel to leave.")))
771
772         ((rx "QUIT" (opt (: " " (let quit-msg (* not-newline)))))
773          (lurk-send-msg (lurk-msg nil nil "QUIT"
774                                   (or quit-msg lurk-default-quit-msg))))
775
776         ((rx (: "NICK" (* whitespace) string-end))
777          (lurk-display-notice nil "Current nick: " lurk-nick))
778
779         ((rx (: "NICK" (+ whitespace) (let nick (+ (not whitespace)))))
780          (if (lurk-connected-p)
781              (lurk-send-msg (lurk-msg nil nil "NICK" nick))
782            (setq lurk-nick nick)
783            (lurk-display-notice nil "Set default nick to '" nick "'")))
784
785         ((rx (: "LIST" (* whitespace) string-end))
786          (lurk-display-notice nil "This command can generate lots of output. Use `LIST -yes' if you're sure."))
787
788         ((rx (: "LIST" (+ whitespace) "-YES" (* whitespace) string-end))
789          (lurk-send-msg (lurk-msg nil nil "LIST")))
790
791         ((rx "MSG "
792              (let to (* (not whitespace)))
793              " "
794              (let text (* not-newline)))
795          (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
796          (lurk-display-message lurk-nick to text))
797
798         ((rx (: (let cmd-str (+ (not whitespace)))
799                 (opt (: " " (let params-str (* not-newline))))))
800          (lurk-send-msg (lurk-msg nil nil (upcase cmd-str)
801                                   (if params-str
802                                       (split-string params-str)
803                                     nil)))))
804
805     (unless (string-empty-p string)
806       (if lurk-current-context
807           (progn
808             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
809                                      lurk-current-context
810                                      string))
811             (lurk-display-message lurk-nick lurk-current-context string))
812         (lurk-display-error "No current context.")))))
813
814 (defvar lurk-history nil
815   "Commands and messages sent in current session.")
816
817
818 (defun lurk-enter ()
819   "Enter current contents of line after prompt."
820   (interactive)
821   (with-current-buffer "*lurk*"
822     (let ((line (buffer-substring lurk-input-marker (point-max))))
823       (push line lurk-history)
824       (setq lurk-history-index nil)
825       (let ((inhibit-read-only t))
826         (delete-region lurk-input-marker (point-max)))
827       (lurk-enter-string line))))
828
829 (defvar lurk-history-index nil)
830
831 (defun lurk-history-cycle (delta)
832   (when lurk-history
833     (with-current-buffer "*lurk*"
834       (if lurk-history-index
835           (setq lurk-history-index
836                 (max 0
837                      (min (- (length lurk-history) 1)
838                           (+ delta lurk-history-index))))
839         (setq lurk-history-index 0))
840       (delete-region lurk-input-marker (point-max))
841       (insert (elt lurk-history lurk-history-index)))))
842
843 (defun lurk-history-next ()
844   (interactive)
845   (lurk-history-cycle -1))
846
847 (defun lurk-history-prev ()
848   (interactive)
849   (lurk-history-cycle +1))
850
851 ;;; Interactive functions
852 ;;
853
854 (defun lurk-cycle-contexts-forward ()
855   (interactive)
856   (lurk-cycle-contexts))
857
858 (defun lurk-cycle-contexts-reverse ()
859   (interactive)
860   (lurk-cycle-contexts t))
861
862 (defvar lurk-zoomed nil
863   "Keeps track of zoom status.")
864
865 (defun lurk-toggle-zoom ()
866   (interactive)
867   (if lurk-zoomed
868       (lurk-zoom-out)
869     (lurk-zoom-in lurk-current-context))
870   (setq lurk-zoomed (not lurk-zoomed)))
871
872 (defun lurk-complete-nick ()
873   (interactive)
874   (when (and (>= (point) lurk-input-marker) lurk-current-context)
875     (let* ((end (max lurk-input-marker (point)))
876            (space-idx (save-excursion
877                         (re-search-backward " " lurk-input-marker t)))
878            (start (if space-idx (+ 1 space-idx) lurk-input-marker))
879            (completion-ignore-case t))
880       (unless (string-prefix-p "/" (buffer-substring start end))
881         (completion-in-region start end (lurk-get-context-users lurk-current-context))))))
882
883
884 ;;; Mode
885 ;;
886
887 (defvar lurk-mode-map
888   (let ((map (make-sparse-keymap)))
889     (define-key map (kbd "RET") 'lurk-enter)
890     (define-key map (kbd "<tab>") 'lurk-complete-nick)
891     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
892     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
893     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
894     (define-key map (kbd "<C-up>") 'lurk-history-prev)
895     (define-key map (kbd "<C-down>") 'lurk-history-next)
896     ;; (when (fboundp 'evil-define-key*)
897     ;;   (evil-define-key* 'insert map
898     ;;                     (kbd "<C-Up>") 'lurk-history-prev
899     ;;                     (kbd "<C-Down>") 'lurk-history-next))
900     map))
901
902 (defvar lurk-mode-map)
903
904 (define-derived-mode lurk-mode text-mode "lurk"
905   "Major mode for LURK.")
906
907 (when (fboundp 'evil-set-initial-state)
908   (evil-set-initial-state 'lurk-mode 'insert))
909
910 ;;; Main start procedure
911 ;;
912
913 (defun lurk ()
914   "Switch to *lurk* buffer."
915   (interactive)
916   (if (get-buffer "*lurk*")
917       (switch-to-buffer "*lurk*")
918     (switch-to-buffer "*lurk*")
919     (lurk-mode)
920     (lurk-setup-buffer))
921   "Started LURK.")
922
923
924 ;;; lurk.el ends here