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