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