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