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