894f4b16a7a96df242abfcd98a6f522e9839f64e
[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 ;;; URL buttons
373
374 (defconst lurk-url-regex
375   (rx (:
376        (group (+ alpha))
377        "://"
378        (group (or (+ (any alnum "." "-"))
379                   (+ (any alnum ":"))))
380        (opt (group (: ":" (+ digit))))
381        (opt (group (: "/"
382                       (opt
383                        (* (any alnum ",.-~/@|:%#=&_"))
384                        (+ (any alnum "-~/@|:%#=&")))))))))
385
386 (defun lurk-click-url (button)
387   (browse-url (button-get button 'url)))
388
389 (defun lurk-buttonify-urls (string)
390   "Turn substrings which look like urls in STRING into clickable buttons."
391   (with-temp-buffer
392     (insert string)
393     (goto-char (point-min))
394     (while (re-search-forward lurk-url-regex nil t)
395       (let ((url (match-string 0)))
396         (make-text-button (match-beginning 0)
397                           (match-end 0)
398                           'action #'lurk-click-url
399                           'url url
400                           'follow-link t
401                           'face 'button
402                           'help-echo "Open URL in browser.")))
403     (buffer-string)))
404
405
406 ;;; Output formatting and highlighting
407 ;;
408
409 ;; Partially-implemented idea: the face text property can be
410 ;; a list of faces, applied in order.  By assigning each context
411 ;; a unique list and keeping track of these in a hash table, we can
412 ;; easily switch the face corresponding to a particular context
413 ;; by modifying the elements of this list.
414 ;;
415 ;; More subtly, we make only the cdrs of this list shared among
416 ;; all text of a given context, allowing the cars to be different
417 ;; and for different elements of the context-specific text to have
418 ;; different styling.
419
420 ;; Additionally, we can allow selective hiding of contexts via
421 ;; the buffer-invisibility-spec.
422
423 (defvar lurk-context-facelists (make-hash-table :test 'equal)
424   "List of seen contexts and associated face lists.")
425
426 (defun lurk-get-context-facelist (context)
427   (let ((facelist (gethash context lurk-context-facelists)))
428     (unless facelist
429       (setq facelist (list 'lurk-text))
430       (puthash context facelist lurk-context-facelists))
431     facelist))
432
433 (defun lurk-display-string (context &rest strings)
434   (with-current-buffer (get-buffer-create "*lurk*")
435     (save-excursion
436       (goto-char lurk-prompt-marker)
437       (let ((inhibit-read-only t)
438             (old-pos (marker-position lurk-prompt-marker))
439             (adaptive-fill-regexp (rx (= 6 anychar)))
440             (fill-column 80)
441             (context-atom (if context (intern context) nil)))
442         (insert-before-markers
443          (propertize (concat (format-time-string "%H:%M") " ")
444                      'face (lurk-get-context-facelist context)
445                      'read-only t
446                      'context context
447                      'invisible context-atom)
448          (propertize (concat (lurk-buttonify-urls (apply #'concat strings)) "\n")
449                      'face (lurk-get-context-facelist context)
450                      'read-only t
451                      'context context
452                      'invisible context-atom))
453         (fill-region old-pos lurk-prompt-marker nil t)))))
454
455 (defun lurk-display-message (from to text)
456   (let ((context (if (eq 'channel (lurk-get-context-type to))
457                      to
458                    (if (equal to lurk-nick) from to))))
459     (lurk-display-string
460      context
461      (pcase (lurk-get-context-type to)
462        ('channel (concat to " <" from "> "))
463        ('nick (concat "[" from " -> " to "] "))
464        (_
465         (error "Unsupported context type")))
466      text)))
467
468 (defun lurk-display-action (from to action-text)
469   (let ((context (if (eq 'channel (lurk-get-context-type to))
470                      to
471                    (if (equal to lurk-nick) from to))))
472     (lurk-display-string
473      context
474      "* " from " " action-text)))
475      
476
477 (defun lurk-display-notice (context &rest notices)
478   (lurk-display-string
479    context
480    lurk-notice-prefix " "
481    (apply #'concat notices)))
482
483 (defun lurk-display-error (&rest messages)
484   (lurk-display-string
485    nil
486    lurk-error-prefix " "
487    (apply #'concat messages)))
488
489 (defun lurk-highlight-context (context)
490   (maphash
491    (lambda (this-context facelist)
492      (if (equal this-context context)
493          (setcar facelist 'lurk-text)
494        (setcar facelist 'lurk-faded)))
495    lurk-context-facelists)
496   (force-window-update "*lurk*"))
497
498 (defun lurk-zoom-in (context)
499   (with-current-buffer "*lurk*"
500     (maphash
501      (lambda (this-context _)
502        (when this-context
503          (let ((this-context-atom (intern this-context)))
504            (if (equal this-context context)
505                (remove-from-invisibility-spec this-context-atom)
506              (add-to-invisibility-spec this-context-atom)))))
507      lurk-context-facelists)
508     (force-window-update "*lurk*")))
509
510 (defun lurk-zoom-out ()
511   (with-current-buffer "*lurk*"
512     (maphash
513      (lambda (this-context _)
514        (let ((this-context-atom (if this-context (intern this-context) nil)))
515          (remove-from-invisibility-spec this-context-atom)))
516      lurk-context-facelists)
517     (force-window-update "*lurk*")))
518
519 ;;; Message evaluation
520 ;;
521
522 (defun lurk-eval-msg-string (string)
523   (if lurk-debug
524       (lurk-display-string nil string))
525   (let* ((msg (lurk-string->msg string)))
526     (pcase (lurk-msg-cmd msg)
527       ("PING"
528        (lurk-send-msg
529         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
530        ;; (lurk-display-notice nil "ping-pong (server initiated)"))
531
532       ("PONG")
533        ;; (lurk-display-notice nil "ping-pong (client initiated)"))
534
535       ("001"
536        (let* ((params (lurk-msg-params msg))
537               (nick (elt params 0))
538               (text (string-join (seq-drop params 1) " ")))
539          (setq lurk-nick nick)
540          (lurk-display-notice nil text)))
541
542       ("353" ; NAMEREPLY
543        (let* ((params (lurk-msg-params msg))
544               (channel (elt params 2))
545               (names (split-string (elt params 3))))
546          (lurk-add-context-users channel names)))
547
548       ("366" ; ENDOFNAMES
549        (let* ((params (lurk-msg-params msg))
550               (channel (elt params 1)))
551          (lurk-display-notice
552           channel
553           (lurk--as-string (length (lurk-get-context-users channel)))
554           " users in " channel)))
555
556       ("331"
557        (let* ((params (lurk-msg-params msg))
558               (channel (elt params 1)))
559          (lurk-display-notice
560           channel
561           "No topic set.")))
562
563       ("332"
564        (let* ((params (lurk-msg-params msg))
565               (channel (elt params 1))
566               (topic (elt params 2)))
567          (lurk-display-notice channel "Topic: " topic)))
568
569       ("333") ; Avoid displaying these
570
571       ((rx (= 3 (any digit)))
572        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
573
574       ((and "JOIN"
575             (guard (equal lurk-nick (lurk-msg-src msg))))
576        (let ((channel (car (lurk-msg-params msg))))
577          (lurk-add-context channel)
578          (lurk-set-current-context channel)
579          (lurk-display-notice channel "Joining channel " channel)
580          (lurk-render-prompt)))
581
582       ("JOIN"
583        (let ((channel (car (lurk-msg-params msg)))
584              (nick (lurk-msg-src msg)))
585          (lurk-add-context-users channel (list nick))
586          (if lurk-show-joins
587              (lurk-display-notice channel nick " joined channel " channel))))
588
589       ((and "PART"
590             (guard (equal lurk-nick (lurk-msg-src msg))))
591        (let ((channel (car (lurk-msg-params msg))))
592          (lurk-display-notice channel "Left channel " channel)
593          (lurk-del-context channel)
594          (if (equal channel lurk-current-context)
595              (lurk-set-current-context (lurk-get-next-context)))
596          (lurk-render-prompt)))
597
598       ("PART"
599        (let ((channel (car (lurk-msg-params msg)))
600              (nick (lurk-msg-src msg)))
601          (lurk-del-context-user channel nick)
602          (if lurk-show-joins
603              (lurk-display-notice channel nick " left channel " channel))))
604
605       ("QUIT"
606        (let ((nick (lurk-msg-src msg))
607              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
608          (lurk-del-user nick)
609          (if lurk-show-joins
610              (lurk-display-notice nil nick " quit: " reason))))
611
612       ((and "NICK"
613             (guard (equal lurk-nick (lurk-msg-src msg))))
614        (setq lurk-nick (car (lurk-msg-params msg)))
615        (lurk-display-notice nil "Set nick to " lurk-nick))
616
617       ("NICK"
618        (let ((old-nick (lurk-msg-src msg))
619              (new-nick (car (lurk-msg-params msg))))
620          (lurk-display-notice nil old-nick " is now known as " new-nick)
621          (lurk-rename-user old-nick new-nick)))
622
623       ("NOTICE"
624        (let ((nick (lurk-msg-src msg))
625              (channel (car (lurk-msg-params msg)))
626              (text (cadr (lurk-msg-params msg))))
627          (pcase text
628            ((rx (: "\01VERSION "
629                    (let version (* (not "\01")))
630                    "\01"))
631             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
632            (_
633             (lurk-display-notice nil text)))))
634
635       ("PRIVMSG"
636        (let* ((from (lurk-msg-src msg))
637               (params (lurk-msg-params msg))
638               (to (car params))
639               (text (cadr params)))
640          (pcase text
641            ("\01VERSION\01"
642             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
643               (lurk-send-msg (lurk-msg nil nil "NOTICE"
644                                        (list from (concat "\01VERSION "
645                                                           version-string
646                                                           "\01")))))
647             (lurk-display-notice nil "CTCP version request received from " from))
648
649            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
650             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
651             (lurk-display-notice from "CTCP ping received from " from))
652
653            ("\01USERINFO\01"
654             (lurk-display-notice from "CTCP userinfo request from " from " (no response sent)"))
655
656            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
657             (lurk-display-action from to action-text))
658
659            (_
660             (lurk-display-message from to text)))))
661       (_
662        (lurk-display-notice nil (lurk-msg->string msg))))))
663
664
665 ;;; Command entering
666 ;;
667
668 (defun lurk-enter-string (string)
669   (if (string-prefix-p "/" string)
670       (pcase (substring string 1)
671         ((rx "DEBUG")
672          (setq lurk-debug (not lurk-debug))
673          (lurk-display-notice nil "Debug mode now " (if lurk-debug "on" "off") "."))
674
675         ((rx (: "CONNECT " (let network (* not-newline))))
676          (lurk-display-notice nil "Attempting to connect to " network "...")
677          (lurk-connect network))
678
679         ((rx (: "TOPIC " (let new-topic (* not-newline))))
680          (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context new-topic)))
681
682         ((rx (: "ME " (let action (* not-newline))))
683          (let ((ctcp-text (concat "\01ACTION " action "\01")))
684            (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
685                                     (list lurk-current-context ctcp-text)))
686            (lurk-display-action lurk-nick lurk-current-context action)))
687
688         ((rx (: "VERSION" " " (let nick (+ (not whitespace)))))
689          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
690                                   (list nick "\01VERSION\01")))
691          (lurk-display-notice nil "CTCP version request sent to " nick))
692
693         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
694          (if (or lurk-current-context channel)
695              (lurk-send-msg (lurk-msg nil nil "PART" (if channel
696                                                          channel
697                                                        lurk-current-context)))
698            (lurk-display-error "No current channel to leave.")))
699
700         ((rx "QUIT" (opt (: " " (let quit-msg (* not-newline)))))
701          (lurk-send-msg (lurk-msg nil nil "QUIT"
702                                   (or quit-msg lurk-default-quit-msg))))
703
704         ((rx (: "NICK" (* whitespace) string-end))
705          (lurk-display-notice nil "Current nick: " lurk-nick))
706
707         ((rx (: "NICK" (+ whitespace) (let nick (+ (not whitespace)))))
708          (if (lurk-connected-p)
709              (lurk-send-msg (lurk-msg nil nil "NICK" nick))
710            (setq lurk-nick nick)
711            (lurk-display-notice nil "Set default nick to '" nick "'")))
712
713         ((rx "LIST")
714          (lurk-display-notice nil "This command can generate lots of output. Use `LIST -yes' if you're sure."))
715
716         ((rx (: "LIST" (+ whitespace) "-YES"))
717          (lurk-send-msg (lurk-msg nil nil "LIST")))
718
719         ((rx "MSG "
720              (let to (* (not whitespace)))
721              " "
722              (let text (* not-newline)))
723          (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
724          (lurk-display-message lurk-nick to text))
725
726         ((rx (: (let cmd-str (+ (not whitespace)))
727                 (opt (: " " (let params-str (* not-newline))))))
728          (lurk-send-msg (lurk-msg nil nil (upcase cmd-str)
729                                   (if params-str
730                                       (split-string params-str)
731                                     nil)))))
732
733     (unless (string-empty-p string)
734       (if lurk-current-context
735           (progn
736             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
737                                      lurk-current-context
738                                      string))
739             (lurk-display-message lurk-nick lurk-current-context string))
740         (lurk-display-error "No current context.")))))
741
742 (defun lurk-enter ()
743   "Enter current contents of line after prompt."
744   (interactive)
745   (with-current-buffer "*lurk*"
746     (let ((line (buffer-substring lurk-input-marker (point-max))))
747       (let ((inhibit-read-only t))
748         (delete-region lurk-input-marker (point-max)))
749       (lurk-enter-string line))))
750
751
752 ;;; Command completion
753 ;;
754
755 ;;; Interactive functions
756 ;;
757
758 (defun lurk-cycle-contexts-forward ()
759   (interactive)
760   (lurk-cycle-contexts))
761
762 (defun lurk-cycle-contexts-reverse ()
763   (interactive)
764   (lurk-cycle-contexts t))
765
766 (defvar lurk-zoomed nil
767   "Keeps track of zoom status.")
768
769 (defun lurk-toggle-zoom ()
770   (interactive)
771   (if lurk-zoomed
772       (lurk-zoom-out)
773     (lurk-zoom-in lurk-current-context))
774   (setq lurk-zoomed (not lurk-zoomed)))
775
776 ;;; Mode
777 ;;
778
779 (defvar lurk-mode-map
780   (let ((map (make-sparse-keymap)))
781     (define-key map (kbd "RET") 'lurk-enter)
782     (define-key map (kbd "<tab>") 'lurk-complete)
783     (define-key map (kbd "C-c C-z") 'lurk-toggle-zoom)
784     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
785     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
786     map))
787
788 (define-derived-mode lurk-mode text-mode "lurk"
789   "Major mode for LURK.")
790
791 (when (fboundp 'evil-set-initial-state)
792   (evil-set-initial-state 'lurk-mode 'insert))
793
794 ;;; Main start procedure
795 ;;
796
797 (defun lurk ()
798   "Switch to *lurk* buffer."
799   (interactive)
800   (if (get-buffer "*lurk*")
801       (switch-to-buffer "*lurk*")
802     (switch-to-buffer "*lurk*")
803     (lurk-mode)
804     (lurk-setup-buffer))
805   "Started LURK.")
806
807
808 ;;; lurk.el ends here