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