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