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