Invisible messages now properly filled.
[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--fill-strings (col indent &rest strings)
409   (with-temp-buffer
410     (setq buffer-invisibility-spec nil)
411     (let ((fill-column col)
412           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
413       (apply #'insert strings)
414       (fill-region (point-min) (point-max) nil t)
415       (buffer-string))))
416
417 (defun lurk-display-string (context prefix &rest strings)
418   (with-current-buffer (get-buffer-create "*lurk*")
419     (save-excursion
420       (goto-char lurk-prompt-marker)
421       (let* ((inhibit-read-only t)
422              (old-pos (marker-position lurk-prompt-marker))
423              (padded-timestamp (concat (format-time-string "%H:%M ")))
424              (padded-prefix (if prefix (concat prefix " ") ""))
425              (context-atom (if context (intern context) nil)))
426         (insert-before-markers
427          (lurk--fill-strings
428           80
429           (+ (length padded-timestamp)
430              (length padded-prefix))
431           (propertize padded-timestamp
432                       'face 'lurk-timestamp
433                       'read-only t
434                       'context context
435                       'invisible context-atom)
436           (propertize padded-prefix
437                       'read-only t
438                       'context context
439                       'invisible context-atom)
440           (propertize (concat (lurk-buttonify-urls (apply #'concat strings)) "\n")
441                       'face (lurk-get-context-facelist context)
442                       'read-only t
443                       'context context
444                       'invisible context-atom)))))))
445
446 (defun lurk-display-message (from to text)
447   (let ((context (if (eq 'channel (lurk-get-context-type to))
448                      to
449                    (if (equal to lurk-nick) from to))))
450     (lurk-display-string
451      context
452      (propertize
453       (pcase (lurk-get-context-type to)
454         ('channel (concat to " <" from ">"))
455         ('nick (concat "[" from " -> " to "]"))
456         (_
457          (error "Unsupported context type")))
458       'face (lurk-get-context-facelist context))
459      text)))
460
461 (defun lurk-display-action (from to action-text)
462   (let ((context (if (eq 'channel (lurk-get-context-type to))
463                      to
464                    (if (equal to lurk-nick) from to))))
465     (lurk-display-string
466      context
467      (concat "* " from)
468      action-text)))
469
470 (defun lurk-display-notice (context &rest notices)
471   (lurk-display-string
472    context
473    (propertize lurk-notice-prefix 'face 'lurk-notice)
474    (apply #'concat notices)))
475
476 (defun lurk-display-error (&rest messages)
477   (lurk-display-string
478    nil
479    (propertize lurk-error-prefix 'face 'lurk-error)
480    (apply #'concat messages)))
481
482 (defun lurk-highlight-context (context)
483   (maphash
484    (lambda (this-context facelist)
485      (if (equal this-context context)
486          (setcar facelist 'lurk-text)
487        (setcar facelist 'lurk-faded)))
488    lurk-context-facelists)
489   (force-window-update "*lurk*"))
490
491 (defun lurk-zoom-in (context)
492   (with-current-buffer "*lurk*"
493     (maphash
494      (lambda (this-context _)
495        (when this-context
496          (let ((this-context-atom (intern this-context)))
497            (if (equal this-context context)
498                (remove-from-invisibility-spec this-context-atom)
499              (add-to-invisibility-spec this-context-atom)))))
500      lurk-context-facelists)
501     (force-window-update "*lurk*")))
502
503 (defun lurk-zoom-out ()
504   (with-current-buffer "*lurk*"
505     (maphash
506      (lambda (this-context _)
507        (let ((this-context-atom (if this-context (intern this-context) nil)))
508          (remove-from-invisibility-spec this-context-atom)))
509      lurk-context-facelists)
510     (force-window-update "*lurk*")))
511
512 (defconst lurk-url-regex
513   (rx (:
514        (group (+ alpha))
515        "://"
516        (group (or (+ (any alnum "." "-"))
517                   (+ (any alnum ":"))))
518        (opt (group (: ":" (+ digit))))
519        (opt (group (: "/"
520                       (opt
521                        (* (any alnum "-/.,#:%=&_"))
522                        (any alnum "-/#:%=&_")))))))
523   "Imperfect regex used to find URLs in plain text.")
524
525 (defun lurk-click-url (button)
526   (browse-url (button-get button 'url)))
527
528 (defun lurk-buttonify-urls (string)
529   "Turn substrings which look like urls in STRING into clickable buttons."
530   (with-temp-buffer
531     (insert string)
532     (goto-char (point-min))
533     (while (re-search-forward lurk-url-regex nil t)
534       (let ((url (match-string 0)))
535         (make-text-button (match-beginning 0)
536                           (match-end 0)
537                           'action #'lurk-click-url
538                           'url url
539                           'follow-link t
540                           'face 'button
541                           'help-echo "Open URL in browser.")))
542     (buffer-string)))
543
544
545 ;;; Message evaluation
546 ;;
547
548 (defun lurk-eval-msg-string (string)
549   (if lurk-debug
550       (lurk-display-string nil nil string))
551   (let* ((msg (lurk-string->msg string)))
552     (pcase (lurk-msg-cmd msg)
553       ("PING"
554        (lurk-send-msg
555         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
556
557       ("PONG")
558
559       ("001"
560        (let* ((params (lurk-msg-params msg))
561               (nick (elt params 0))
562               (text (string-join (seq-drop params 1) " ")))
563          (setq lurk-nick nick)
564          (lurk-display-notice nil text)))
565
566       ("353" ; NAMEREPLY
567        (let* ((params (lurk-msg-params msg))
568               (channel (elt params 2))
569               (names (split-string (elt params 3))))
570          (lurk-add-context-users channel names)))
571
572       ("366" ; ENDOFNAMES
573        (let* ((params (lurk-msg-params msg))
574               (channel (elt params 1)))
575          (lurk-display-notice
576           channel
577           (lurk--as-string (length (lurk-get-context-users channel)))
578           " users in " channel)))
579
580       ("331"
581        (let* ((params (lurk-msg-params msg))
582               (channel (elt params 1)))
583          (lurk-display-notice
584           channel
585           "No topic set.")))
586
587       ("332"
588        (let* ((params (lurk-msg-params msg))
589               (channel (elt params 1))
590               (topic (elt params 2)))
591          (lurk-display-notice channel "Topic: " topic)))
592
593       ("333") ; Avoid displaying these
594
595       ((rx (= 3 (any digit)))
596        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
597
598       ((and "JOIN"
599             (guard (equal lurk-nick (lurk-msg-src msg))))
600        (let ((channel (car (lurk-msg-params msg))))
601          (lurk-add-context channel)
602          (lurk-set-current-context channel)
603          (lurk-display-notice channel "Joining channel " channel)
604          (lurk-render-prompt)))
605
606       ("JOIN"
607        (let ((channel (car (lurk-msg-params msg)))
608              (nick (lurk-msg-src msg)))
609          (lurk-add-context-users channel (list nick))
610          (if lurk-show-joins
611              (lurk-display-notice channel nick " joined channel " channel))))
612
613       ((and "PART"
614             (guard (equal lurk-nick (lurk-msg-src msg))))
615        (let ((channel (car (lurk-msg-params msg))))
616          (lurk-display-notice channel "Left channel " channel)
617          (lurk-del-context channel)
618          (if (equal channel lurk-current-context)
619              (lurk-set-current-context (lurk-get-next-context)))
620          (lurk-render-prompt)))
621
622       ("PART"
623        (let ((channel (car (lurk-msg-params msg)))
624              (nick (lurk-msg-src msg)))
625          (lurk-del-context-user channel nick)
626          (if lurk-show-joins
627              (lurk-display-notice channel nick " left channel " channel))))
628
629       ((and "KICK")
630        (let ((kicker-nick (lurk-msg-src msg))
631              (channel (car (lurk-msg-params msg)))
632              (nick (cadr (lurk-msg-params msg)))
633              (reason (caddr (lurk-msg-params msg))))
634          (if (equal nick lurk-nick)
635              (progn
636                (lurk-display-notice channel kicker-nick " kicked you from " channel ": " reason)
637                (lurk-del-context channel)
638                (if (equal channel lurk-current-context)
639                    (lurk-set-current-context (lurk-get-next-context)))
640                (lurk-render-prompt))
641            (lurk-del-context-user channel nick)
642            (lurk-display-notice channel kicker-nick " kicked " nick " from " channel ": " reason))))
643
644       ("QUIT"
645        (let ((nick (lurk-msg-src msg))
646              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
647          (lurk-del-user nick)
648          (if lurk-show-joins
649              (lurk-display-notice nil nick " quit: " reason))))
650
651       ((and "NICK"
652             (guard (equal lurk-nick (lurk-msg-src msg))))
653        (setq lurk-nick (car (lurk-msg-params msg)))
654        (lurk-display-notice nil "Set nick to " lurk-nick))
655
656       ("NICK"
657        (let ((old-nick (lurk-msg-src msg))
658              (new-nick (car (lurk-msg-params msg))))
659          (lurk-display-notice nil old-nick " is now known as " new-nick)
660          (lurk-rename-user old-nick new-nick)))
661
662       ("NOTICE"
663        (let ((nick (lurk-msg-src msg))
664              (channel (car (lurk-msg-params msg)))
665              (text (cadr (lurk-msg-params msg))))
666          (pcase text
667            ((rx (: "\01VERSION "
668                    (let version (* (not "\01")))
669                    "\01"))
670             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
671            (_
672             (lurk-display-notice nil text)))))
673
674       ("PRIVMSG"
675        (let* ((from (lurk-msg-src msg))
676               (params (lurk-msg-params msg))
677               (to (car params))
678               (text (cadr params)))
679          (pcase text
680            ("\01VERSION\01"
681             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
682               (lurk-send-msg (lurk-msg nil nil "NOTICE"
683                                        (list from (concat "\01VERSION "
684                                                           version-string
685                                                           "\01")))))
686             (lurk-display-notice nil "CTCP version request received from " from))
687
688            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
689             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
690             (lurk-display-notice from "CTCP ping received from " from))
691
692            ("\01USERINFO\01"
693             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
694
695            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
696             (lurk-display-action from to action-text))
697
698            (_
699             (lurk-display-message from to text)))))
700       (_
701        (lurk-display-notice nil (lurk-msg->string msg))))))
702
703
704 ;;; Command entering
705 ;;
706
707 (defun lurk-enter-string (string)
708   (if (string-prefix-p "/" string)
709       (pcase (substring string 1)
710         ((rx "DEBUG")
711          (setq lurk-debug (not lurk-debug))
712          (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
713
714         ((rx (: "CONNECT " (let network (* not-newline))))
715          (lurk-display-notice nil "Attempting to connect to " network "...")
716          (lurk-connect network))
717
718         ((rx (: "TOPIC " (let new-topic (* not-newline))))
719          (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context new-topic)))
720
721         ((rx (: "ME " (let action (* not-newline))))
722          (let ((ctcp-text (concat "\01ACTION " action "\01")))
723            (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
724                                     (list lurk-current-context ctcp-text)))
725            (lurk-display-action lurk-nick lurk-current-context action)))
726
727         ((rx (: "VERSION" " " (let nick (+ (not whitespace)))))
728          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
729                                   (list nick "\01VERSION\01")))
730          (lurk-display-notice nil "CTCP version request sent to " nick))
731
732         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
733          (if (or lurk-current-context channel)
734              (lurk-send-msg (lurk-msg nil nil "PART" (if channel
735                                                          channel
736                                                        lurk-current-context)))
737            (lurk-display-error "No current channel to leave.")))
738
739         ((rx "QUIT" (opt (: " " (let quit-msg (* not-newline)))))
740          (lurk-send-msg (lurk-msg nil nil "QUIT"
741                                   (or quit-msg lurk-default-quit-msg))))
742
743         ((rx (: "NICK" (* whitespace) string-end))
744          (lurk-display-notice nil "Current nick: " lurk-nick))
745
746         ((rx (: "NICK" (+ whitespace) (let nick (+ (not whitespace)))))
747          (if (lurk-connected-p)
748              (lurk-send-msg (lurk-msg nil nil "NICK" nick))
749            (setq lurk-nick nick)
750            (lurk-display-notice nil "Set default nick to '" nick "'")))
751
752         ((rx "LIST")
753          (lurk-display-notice nil "This command can generate lots of output. Use `LIST -yes' if you're sure."))
754
755         ((rx (: "LIST" (+ whitespace) "-YES"))
756          (lurk-send-msg (lurk-msg nil nil "LIST")))
757
758         ((rx "MSG "
759              (let to (* (not whitespace)))
760              " "
761              (let text (* not-newline)))
762          (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
763          (lurk-display-message lurk-nick to text))
764
765         ((rx (: (let cmd-str (+ (not whitespace)))
766                 (opt (: " " (let params-str (* not-newline))))))
767          (lurk-send-msg (lurk-msg nil nil (upcase cmd-str)
768                                   (if params-str
769                                       (split-string params-str)
770                                     nil)))))
771
772     (unless (string-empty-p string)
773       (if lurk-current-context
774           (progn
775             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
776                                      lurk-current-context
777                                      string))
778             (lurk-display-message lurk-nick lurk-current-context string))
779         (lurk-display-error "No current context.")))))
780
781 (defvar lurk-history nil
782   "Commands and messages sent in current session.")
783
784
785 (defun lurk-enter ()
786   "Enter current contents of line after prompt."
787   (interactive)
788   (with-current-buffer "*lurk*"
789     (let ((line (buffer-substring lurk-input-marker (point-max))))
790       (push line lurk-history)
791       (setq lurk-history-index nil)
792       (let ((inhibit-read-only t))
793         (delete-region lurk-input-marker (point-max)))
794       (lurk-enter-string line))))
795
796 (defvar lurk-history-index nil)
797
798 (defun lurk-history-cycle (delta)
799   (when lurk-history
800     (with-current-buffer "*lurk*"
801       (if lurk-history-index
802           (setq lurk-history-index
803                 (max 0
804                      (min (- (length lurk-history) 1)
805                           (+ delta lurk-history-index))))
806         (setq lurk-history-index 0))
807       (delete-region lurk-input-marker (point-max))
808       (insert (elt lurk-history lurk-history-index)))))
809
810 (defun lurk-history-next ()
811   (interactive)
812   (lurk-history-cycle -1))
813
814 (defun lurk-history-prev ()
815   (interactive)
816   (lurk-history-cycle +1))
817
818 ;;; Interactive functions
819 ;;
820
821 (defun lurk-cycle-contexts-forward ()
822   (interactive)
823   (lurk-cycle-contexts))
824
825 (defun lurk-cycle-contexts-reverse ()
826   (interactive)
827   (lurk-cycle-contexts t))
828
829 (defvar lurk-zoomed nil
830   "Keeps track of zoom status.")
831
832 (defun lurk-toggle-zoom ()
833   (interactive)
834   (if lurk-zoomed
835       (lurk-zoom-out)
836     (lurk-zoom-in lurk-current-context))
837   (setq lurk-zoomed (not lurk-zoomed)))
838
839 (defun lurk-complete-nick ()
840   (interactive)
841   (when (and (>= (point) lurk-input-marker) lurk-current-context)
842     (let* ((end (max lurk-input-marker (point)))
843            (space-idx (save-excursion
844                         (re-search-backward " " lurk-input-marker t)))
845            (start (if space-idx (+ 1 space-idx) lurk-input-marker)))
846       (unless (string-prefix-p "/" (buffer-substring start end))
847         (completion-in-region start end (lurk-get-context-users lurk-current-context))))))
848
849
850 ;;; Mode
851 ;;
852
853 (defvar lurk-mode-map
854   (let ((map (make-sparse-keymap)))
855     (define-key map (kbd "RET") 'lurk-enter)
856     (define-key map (kbd "<tab>") 'lurk-complete-nick)
857     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
858     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
859     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
860     (define-key map (kbd "<C-up>") 'lurk-history-prev)
861     (define-key map (kbd "<C-down>") 'lurk-history-next)
862     ;; (when (fboundp 'evil-define-key*)
863     ;;   (evil-define-key* 'insert map
864     ;;                     (kbd "<C-Up>") 'lurk-history-prev
865     ;;                     (kbd "<C-Down>") 'lurk-history-next))
866     map))
867
868 (defvar lurk-mode-map)
869
870 (define-derived-mode lurk-mode text-mode "lurk"
871   "Major mode for LURK.")
872
873 (when (fboundp 'evil-set-initial-state)
874   (evil-set-initial-state 'lurk-mode 'insert))
875
876 ;;; Main start procedure
877 ;;
878
879 (defun lurk ()
880   "Switch to *lurk* buffer."
881   (interactive)
882   (if (get-buffer "*lurk*")
883       (switch-to-buffer "*lurk*")
884     (switch-to-buffer "*lurk*")
885     (lurk-mode)
886     (lurk-setup-buffer))
887   "Started LURK.")
888
889
890 ;;; lurk.el ends here