Added context switching primitives.
[lurk.git] / murk.el
1 ;;; murk.el --- Multiserver Unibuffer iRc Klient -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2024 plugd
4
5 ;; Author: plugd <plugd@thelambdalab.xyz>
6 ;; Created: 11 May 2024
7 ;; Version: 0.0
8 ;; Homepage: http://thelambdalab.xyz/murk
9 ;; Keywords: comm
10 ;; Package-Requires: ((emacs "26.1"))
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 ;; A very simple IRC server which uses only a single buffer.
30
31 ;;; Code:
32
33 (provide 'murk)
34
35 (require 'cl-lib)
36
37
38 ;;; Customizations
39
40 (defgroup murk nil
41   "Multiserver Unibuffer iRc Klient"
42   :group 'network)
43
44 (defcustom murk-default-nick "plugd"
45   "Default nick."
46   :type '(string))
47
48 (defcustom murk-default-quit-msg "Bye"
49   "Default quit message when none supplied."
50   :type '(string))
51
52 (defcustom murk-networks
53   '(("debug" "localhost" 6697)
54     ("libera" "irc.libera.chat" 6697)
55     ("tilde" "tilde.chat" 6697)
56     ("freenode" "chat.freenode.net" 6697)
57     ("mbr" "mbrserver.com" 6667 :notls))
58   "IRC networks."
59   :type '(alist :key-type string))
60
61 (defcustom murk-show-joins nil
62   "Set to non-nil to be notified of joins, parts and quits.")
63
64 (defcustom murk-display-header t
65   "If non-nil, use buffer header to display current host and channel."
66   :type '(boolean))
67
68
69 ;;; Faces
70 ;;
71
72 (defface murk-text
73   '((t :inherit default))
74   "Face used for murk text.")
75
76 (defface murk-prompt
77   '((t :inherit font-lock-keyword-face))
78   "Face used for the prompt.")
79
80 (defface murk-context
81   '((t :inherit murk-context))
82   "Face used for the context name in the prompt.")
83
84 (defface murk-faded
85   '((t :inherit shadow))
86   "Face used for faded murk text.")
87
88 (defface murk-timestamp
89   '((t :inherit shadow))
90   "Face used for timestamps.")
91
92 (defface murk-error
93   '((t :inherit error))
94   "Face used for murk error text.")
95
96 (defface murk-notice
97   '((t :inherit warning))
98   "Face used for murk notice text.")
99
100
101 ;;; Global variables
102 ;;
103
104 (defvar murk-version "Murk v0.0"
105   "Value of this string is used in response to CTCP version queries.")
106
107 (defvar murk-notice-prefix "-!-")
108 (defvar murk-error-prefix "!!!")
109 (defvar murk-prompt-string ">")
110
111 (defvar murk-debug nil
112   "If non-nil, enable debug mode.")
113
114
115 ;;; Utility procedures
116 ;;
117
118 (defun murk--filtered-join (&rest args)
119   (string-join (seq-filter (lambda (el) el) args) " "))
120
121 (defun murk--as-string (obj)
122   (if obj
123       (with-output-to-string (princ obj))
124     nil))
125
126
127 ;;; Network processes
128 ;;
129
130 (defvar murk-connection-table nil
131   "An alist associating servers to connection information.
132 This includes the process and the response string.")
133
134 (defun murk-connection-process (server)
135   (elt (assoc server murk-connection-table) 1))
136
137 (defun murk-connection-nick (server)
138   (elt (assoc server murk-connection-table) 2))
139
140 (defun murk-set-connection-nick (server nick)
141   (setf (elt (assoc server murk-connection-table) 2) nick))
142
143 (defun murk-connection-response (server)
144   (elt (assoc server murk-connection-table) 3))
145
146 (defun murk-set-connection-response (server string)
147   (setf (elt (assoc server murk-connection-table) 3) string))
148
149 (defun murk-connection-new (server process nick)
150   (add-to-list 'murk-connection-table
151                (list server process nick "")))
152
153 (defun murk-connection-remove (server)
154   (setq murk-connection-table
155         (seq-remove (lambda (row) (equal (car row) server))
156                     murk-connection-table)))
157
158 (defun murk-make-server-filter (server)
159   (lambda (_proc string)
160     (dolist (line (split-string (concat (murk-connection-response server) string)
161                                 "\n"))
162       (if (string-suffix-p "\r" line)
163           (murk-eval-msg-string server (string-trim line))
164         (murk-set-connection-response server line)))))
165
166 (defun murk-make-server-sentinel (server)
167   (lambda (_proc string)
168     (unless (equal "open" (string-trim string))
169       (murk-display-error "Disconnected from server.")
170       (murk-connection-remove server)
171       (murk-remove-server-contexts server)
172       (murk-render-prompt))))
173
174 (defun murk-start-process (server)
175   (let* ((row (assoc server murk-networks))
176          (host (elt row 1))
177          (port (elt row 2))
178          (flags (seq-drop row 3)))
179     (make-network-process :name (concat "murk-" server)
180                           :host host
181                           :service port
182                           :family nil
183                           :filter (murk-make-server-filter server)
184                           :sentinel (murk-make-server-sentinel server)
185                           :nowait nil
186                           :tls-parameters (if (memq :notls flags)
187                                               nil
188                                             (cons 'gnutls-x509pki
189                                                   (gnutls-boot-parameters
190                                                    :type 'gnutls-x509pki
191                                                    :hostname host)))
192                           :buffer "*murk*")))
193
194 (defvar murk-ping-period 60)
195
196 ;; IDEA: Have a single ping timer which pings all connected hosts
197
198 (defun murk-connect (server)
199   (if (assoc server murk-connection-table)
200       (murk-display-error "Already connected to this network")
201     (if (not (assoc server murk-networks))
202         (murk-display-error "Network '" server "' is unknown.")
203       (let ((proc (murk-start-process server)))
204         (murk-connection-new server proc murk-default-nick))
205       (murk-send-msg server (murk-msg nil nil "USER" murk-default-nick 0 "*" murk-default-nick))
206       (murk-send-msg server (murk-msg nil nil "NICK" murk-default-nick))
207       (murk-add-context (list server))
208       (murk-render-prompt))))
209
210 (defun murk-send-msg (server msg)
211   (if murk-debug
212       (murk-display-string nil nil (murk-msg->string msg)))
213   (let ((proc (murk-connection-process server)))
214     (if (and proc (eq (process-status proc) 'open))
215         (process-send-string proc (concat (murk-msg->string msg) "\r\n"))
216       (murk-display-error "No server connection established"))))
217
218
219 ;;; Server messages
220 ;;
221
222 (defun murk-msg (tags src cmd &rest params)
223   (list (murk--as-string tags)
224         (murk--as-string src)
225         (upcase (murk--as-string cmd))
226         (mapcar #'murk--as-string
227                 (if (and params (listp (elt params 0)))
228                     (elt params 0)
229                   params))))
230
231 (defun murk-msg-tags (msg) (elt msg 0))
232 (defun murk-msg-src (msg) (elt msg 1))
233 (defun murk-msg-cmd (msg) (elt msg 2))
234 (defun murk-msg-params (msg) (elt msg 3))
235 (defun murk-msg-trail (msg)
236   (let ((params (murk-msg-params msg)))
237     (if params
238         (elt params (- (length params) 1)))))
239
240 (defvar murk-msg-regex
241   (rx
242    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
243         (* whitespace))
244    (opt (: ":" (: (group (* (not (any space "!" "@"))))
245                   (* (not (any space)))))
246         (* whitespace))
247    (group (: (* (not whitespace))))
248    (* whitespace)
249    (opt (group (+ not-newline))))
250   "Regex used to parse IRC messages.
251 Note that this regex is incomplete.  Noteably, we discard the non-nick
252 portion of the source component of the message, as mURK doesn't use this.")
253
254 (defun murk-string->msg (string)
255   (if (string-match murk-msg-regex string)
256       (let* ((tags (match-string 1 string))
257              (src (match-string 2 string))
258              (cmd (upcase (match-string 3 string)))
259              (params-str (match-string 4 string))
260              (params
261               (if params-str
262                   (let* ((idx (seq-position params-str ?:))
263                          (l (split-string (string-trim (substring params-str 0 idx))))
264                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
265                     (append l r))
266                 nil)))
267         (apply #'murk-msg (append (list tags src cmd) params)))
268     (error "Failed to parse string %s" string)))
269
270 (defun murk-msg->string (msg)
271   (let ((tags (murk-msg-tags msg))
272         (src (murk-msg-src msg))
273         (cmd (murk-msg-cmd msg))
274         (params (murk-msg-params msg)))
275     (murk--filtered-join
276      (if tags (concat "@" tags) nil)
277      (if src (concat ":" src) nil)
278      cmd
279      (if (> (length params) 1)
280          (string-join (seq-take params (- (length params) 1)) " ")
281        nil)
282      (if (> (length params) 0)
283          (concat ":" (elt params (- (length params) 1)))
284        nil))))
285
286
287 ;;; Contexts
288 ;;
289
290 ;; A context is a list (server channel users) identifying the server
291 ;; and channel.  The tail of the list contains the nicks of users
292 ;; present in the channel.
293 ;;
294 ;; Each server has a special context (server) used for messages
295 ;; to/from the server itself.
296
297 (defvar murk-contexts nil
298   "List of currently-available contexts.
299 The head of this list is always the current context.")
300
301 (defun murk-current-context ()
302   "Return the current context."
303   (if murk-contexts
304       (car murk-contexts)
305     nil))
306
307 (defun murk-contexts-equal (c1 c2)
308   (if (murk-server-context-p c1)
309       (and (murk-server-context-p c2)
310            (equal (murk-context-server c1)
311                   (murk-context-server c2)))
312     (and (not (murk-server-context-p c2))
313          (equal (seq-take c1 2)
314                 (seq-take c2 2)))))
315
316 (defun murk-context-server (ctx)
317   (elt ctx 0))
318
319 (defun murk-context-channel (ctx)
320   (elt ctx 1))
321
322 (defun murk-context-users (ctx)
323   (elt ctx 2))
324
325 (defun murk-set-context-users (ctx users)
326   (setcar (cddr ctx) users))
327
328 (defun murk-server-context-p (ctx)
329   (not (cdr ctx)))
330
331 (defun murk-add-context (ctx)
332   (add-to-list 'murk-contexts ctx))
333
334 (defun murk-remove-context (ctx)
335   (setq murk-contexts
336         (seq-remove
337          (lambda (this-ctx)
338            (murk-contexts-equal this-ctx ctx))
339          murk-contexts)))
340
341 (defun murk-remove-server-contexts (server)
342   (setq murk-contexts
343         (seq-remove (lambda (row) (equal (car row) server))
344                     murk-contexts)))
345
346 (defun murk-context->string (ctx)
347    (if (murk-server-context-p ctx)
348        (concat "[" (murk-context-server ctx) "]")
349      (concat (murk-context-channel ctx) "@"
350              (murk-context-server ctx))))
351
352 (defun murk-string->context (string)
353   (if (not (string-prefix-p "#" string))
354       (murk-get-context string)
355     (let* ((parts (string-split string "@"))
356            (channel (elt parts 0))
357            (server (elt parts 1)))
358       (murk-get-context server channel))))
359
360 (defun murk-get-context (server &optional channel)
361   (if channel
362       (let ((test-ctx (list server channel)))
363         (seq-find (lambda (ctx)
364                     (equal (seq-take ctx 2) test-ctx))
365                   murk-contexts))
366     (car (member (list server) murk-contexts))))
367
368 (defun murk-cycle-contexts (&optional reverse)
369   (setq murk-contexts
370         (if reverse
371             (let ((nminus1 (- (length murk-contexts) 1)))
372               (cons
373                (elt murk-contexts nminus1)
374                (seq-take murk-contexts nminus1)))
375           (append (cdr murk-contexts) (list (car murk-contexts))))))
376
377 (defun murk-switch-to-context (ctx)
378   (setq murk-contexts
379         (let* ((new-head (memq ctx murk-contexts))
380                (new-tail (take (- (length murk-contexts)
381                                   (length new-head)))))
382           (append new-head new-tail))))
383
384 (defun murk-add-context-users (ctx users)
385   (murk-set-context-users
386    ctx
387    (cl-union users (murk-context-users ctx))))
388
389 (defun murk-del-context-user (ctx user)
390   (murk-set-context-users
391    ctx
392    (delete user (murk-context-users ctx))))
393
394 (defun murk-del-server-user (server user)
395   (dolist (ctx murk-contexts)
396     (if (equal (murk-context-server ctx) server)
397         (murk-del-context-user ctx user))))
398
399 (defun murk-rename-server-user (server old-nick new-nick)
400   (dolist (ctx murk-contexts)
401     (when (and (equal (murk-context-server ctx) server)
402                (member old-nick (murk-context-users ctx)))
403       (murk-del-context-user ctx old-nick)
404       (murk-add-context-users ctx (list new-nick)))))
405
406 ;;; Buffer
407 ;;
408
409 (defvar murk-prompt-marker nil
410   "Marker for prompt position in murk buffer.")
411
412 (defvar murk-input-marker nil
413   "Marker for prompt position in murk buffer.")
414
415 (defun murk-render-prompt ()
416   (with-current-buffer "*murk*"
417     (let ((update-point (= murk-input-marker (point)))
418           (update-window-points (mapcar (lambda (w)
419                                           (list (= (window-point w) murk-input-marker)
420                                                 w))
421                                         (get-buffer-window-list nil nil t))))
422       (save-excursion
423         (set-marker-insertion-type murk-prompt-marker nil)
424         (set-marker-insertion-type murk-input-marker t)
425         (let ((inhibit-read-only t))
426           (delete-region murk-prompt-marker murk-input-marker)
427           (goto-char murk-prompt-marker)
428           (insert
429            (propertize (let ((ctx (murk-current-context)))
430                          (if ctx
431                              (murk-context->string ctx)
432                            ""))
433                        'face 'murk-context
434                        'read-only t)
435            (propertize murk-prompt-string
436                        'face 'murk-prompt
437                        'read-only t)
438            (propertize " " ; Need this to be separate to mark it as rear-nonsticky
439                        'read-only t
440                        'rear-nonsticky t)))
441         (set-marker-insertion-type murk-input-marker nil))
442       (if update-point
443           (goto-char murk-input-marker))
444       (dolist (v update-window-points)
445         (if (car v)
446             (set-window-point (cadr v) murk-input-marker))))))
447   
448 (defun murk-setup-header ()
449   (with-current-buffer "*murk*"
450     (setq-local header-line-format
451                 '((:eval
452                    (let* ((ctx (murk-current-context)))
453                      (if ctx
454                          (let ((server (murk-context-server ctx)))
455                            (concat
456                             "Network: " server ", "
457                             (if (murk-server-context-p ctx)
458                                 "Server"
459                               (concat
460                                "Channel: "
461                                (murk-context-channel ctx)
462                                " ("
463                                (number-to-string
464                                 (length (murk-context-users ctx)))
465                                ")"))))
466                        "No connection")))))))
467
468 (defun murk-setup-buffer ()
469   (with-current-buffer (get-buffer-create "*murk*")
470     (setq-local scroll-conservatively 1)
471     (setq-local buffer-invisibility-spec nil)
472     (if (markerp murk-prompt-marker)
473         (set-marker murk-prompt-marker (point-max))
474       (setq murk-prompt-marker (point-max-marker)))
475     (if (markerp murk-input-marker)
476         (set-marker murk-input-marker (point-max))
477       (setq murk-input-marker (point-max-marker)))
478     (goto-char (point-max))
479     (murk-render-prompt)
480     (if murk-display-header
481         (murk-setup-header))))
482
483 (defun murk-clear-buffer ()
484   "Completely erase all non-prompt and non-input text from murk buffer."
485   (with-current-buffer "*murk*"
486     (let ((inhibit-read-only t))
487       (delete-region (point-min) murk-prompt-marker))))
488
489
490 ;;; Output formatting and highlighting
491 ;;
492
493 (defun murk--fill-strings (col indent &rest strings)
494   (with-temp-buffer
495     (setq buffer-invisibility-spec nil)
496     (let ((fill-column col)
497           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
498       (apply #'insert strings)
499       (fill-region (point-min) (point-max) nil t)
500       (buffer-string))))
501
502 (defun murk-display-string (context prefix &rest strings)
503   (with-current-buffer "*murk*"
504     (save-excursion
505       (goto-char murk-prompt-marker)
506       (let* ((inhibit-read-only t)
507              (old-pos (marker-position murk-prompt-marker))
508              (padded-timestamp (concat (format-time-string "%H:%M ")))
509              (padded-prefix (if prefix (concat prefix " ") ""))
510              (context-atom (if context (intern (murk-context->string context)) nil)))
511         (insert-before-markers
512          (murk--fill-strings
513           80
514           (+ (length padded-timestamp)
515              (length padded-prefix))
516           (propertize padded-timestamp
517                       'face 'murk-timestamp
518                       'read-only t
519                       'context context
520                       'invisible context-atom)
521           (propertize padded-prefix
522                       'read-only t
523                       'context context
524                       'invisible context-atom)
525           (murk-add-formatting
526            (propertize (concat (apply #'murk-buttonify-urls strings) "\n")
527                        'read-only t
528                        'context context
529                        'invisible context-atom)))))))
530   (murk-scroll-windows-to-last-line))
531
532 (defun murk-display-message (server from to text)
533   (let ((context (if (string-prefix-p "#" to)
534                      (murk-get-context server to)
535                    (murk-get-context server))))
536     (murk-display-string
537      context
538      (if (murk-server-context-p context)
539          (concat "[" from " -> " to "]")
540        (concat (murk-context->string context) " <" from ">"))
541      text)))
542
543 (defun murk-display-action (server from to action-text)
544   (let ((context (if (string-prefix-p "#" to)
545                      (murk-get-context server to)
546                    (murk-get-context server))))
547     (murk-display-string
548      context
549      (concat (murk-context->string context) " *")
550      from " " action-text)))
551
552 (defun murk-display-notice (context &rest notices)
553   (murk-display-string
554    context
555    (propertize murk-notice-prefix 'face 'murk-notice)
556    (apply #'concat notices)))
557
558 (defun murk-display-error (&rest messages)
559   (murk-display-string
560    nil
561    (propertize murk-error-prefix 'face 'murk-error)
562    (apply #'concat messages)))
563
564 (defun murk--start-of-final-line ()
565   (with-current-buffer "*murk*"
566     (save-excursion
567       (goto-char (point-max))
568       (line-beginning-position))))
569
570 (defun murk-scroll-windows-to-last-line ()
571   (with-current-buffer "*murk*"
572     (dolist (window (get-buffer-window-list))
573       (if (>= (window-point window) (murk--start-of-final-line))
574           (with-selected-window window
575             (recenter -1))))))
576
577 (defconst murk-url-regex
578   (rx (:
579        (group (+ alpha))
580        "://"
581        (group (or (+ (any alnum "." "-"))
582                   (+ (any alnum ":"))))
583        (opt (group (: ":" (+ digit))))
584        (opt (group (: "/"
585                       (opt
586                        (* (any alnum "-/.,#:%=&_?~@+"))
587                        (any alnum "-/#:%=&_~@+")))))))
588   "Imperfect regex used to find URLs in plain text.")
589
590 (defun murk-click-url (button)
591   (browse-url (button-get button 'url)))
592
593 (defun murk-buttonify-urls (&rest strings)
594   "Turn substrings which look like urls in STRING into clickable buttons."
595   (with-temp-buffer
596     (apply #'insert strings)
597     (goto-char (point-min))
598     (while (re-search-forward murk-url-regex nil t)
599       (let ((url (match-string 0)))
600         (make-text-button (match-beginning 0)
601                           (match-end 0)
602                           'action #'murk-click-url
603                           'url url
604                           'follow-link t
605                           'face 'button
606                           'help-echo "Open URL in browser.")))
607     (buffer-string)))
608
609 (defun murk-add-formatting (string)
610   (with-temp-buffer
611     (insert string)
612     (goto-char (point-min))
613     (let ((bold nil)
614           (italics nil)
615           (underline nil)
616           (strikethrough nil)
617           (prev-point (point)))
618       (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
619                                         (: "\x03" (+ digit) (opt "," (* digit)))))
620                                 nil t)
621         (let ((beg (+ (match-beginning 0) 1)))
622           (if bold
623               (add-face-text-property prev-point beg '(:weight bold)))
624           (if italics
625               (add-face-text-property prev-point beg '(:slant italic)))
626           (if underline
627               (add-face-text-property prev-point beg '(:underline t)))
628           (if strikethrough
629               (add-face-text-property prev-point beg '(:strike-through t)))
630           (pcase (match-string 0)
631             ("\x02" (setq bold (not bold)))
632             ("\x1D" (setq italics (not italics)))
633             ("\x1F" (setq underline (not underline)))
634             ("\x1E" (setq strikethrough (not strikethrough)))
635             ("\x0F" ; Reset
636              (setq bold nil)
637              (setq italics nil)
638              (setq underline nil)
639              (setq strikethrough nil))
640             (_))
641           (delete-region (match-beginning 0) (match-end 0))
642           (setq prev-point (point)))))
643     (buffer-string)))
644
645
646 ;;; Message evaluation
647 ;;
648
649 (defun murk-eval-msg-string (server string)
650   (if murk-debug
651       (murk-display-string nil nil string))
652   (let* ((msg (murk-string->msg string)))
653     (pcase (murk-msg-cmd msg)
654       ("PING"
655        (murk-send-msg server
656         (murk-msg nil nil "PONG" (murk-msg-params msg))))
657
658       ("PONG")
659
660       ("001" ; RPL_WELCOME
661        (let* ((params (murk-msg-params msg))
662               (nick (elt params 0))
663               (text (string-join (seq-drop params 1) " ")))
664          (murk-set-connection-nick server nick)
665          (murk-display-notice nil text)))
666
667       ("353" ; NAMEREPLY
668        (let* ((params (murk-msg-params msg))
669               (channel (elt params 2))
670               (names (split-string (elt params 3)))
671               (ctx (murk-get-context server channel)))
672          (if ctx
673              (murk-add-context-users ctx names)
674            (murk-display-notice nil "Users in " channel
675                                 ": " (string-join names " ")))))
676
677       ("366" ; ENDOFNAMES
678        (let* ((params (murk-msg-params msg))
679               (channel (elt params 1))
680               (ctx (murk-get-context server channel)))
681          (if ctx
682              (murk-display-notice
683               ctx
684               (murk--as-string (length (murk-context-users ctx)))
685               " users in " channel)
686            (murk-display-notice nil "End of " channel " names list."))))
687
688       ("331" ; RPL_NOTOPIC
689        (let* ((params (murk-msg-params msg))
690               (channel (elt params 1))
691               (ctx (murk-get-context server channel)))
692          (murk-display-notice ctx "No topic set.")))
693
694       ("332" ; RPL_TOPIC
695        (let* ((params (murk-msg-params msg))
696               (channel (elt params 1))
697               (topic (elt params 2))
698               (ctx (murk-get-context server channel)))
699          (murk-display-notice ctx "Topic: " topic)))
700
701       ((rx (= 3 (any digit)))
702        (murk-display-notice nil (mapconcat 'identity (cdr (murk-msg-params msg)) " ")))
703
704       ((and "JOIN"
705             (guard (equal (murk-connection-nick server)
706                           (murk-msg-src msg))))
707        (let ((channel (car (murk-msg-params msg))))
708          (murk-add-context (list server channel nil))
709          (murk-display-notice (murk-current-context)
710                               "Joining channel " channel " on " server)
711          (murk-render-prompt)))
712
713       ("JOIN"
714        (let* ((channel (car (murk-msg-params msg)))
715               (nick (murk-msg-src msg))
716               (ctx (murk-get-context server channel)))
717          (murk-add-context-users ctx (list nick))
718          (if murk-show-joins
719              (murk-display-notice ctx nick " joined channel " channel
720                                   " on " server))))
721
722       ((and "PART"
723             (guard (equal (murk-connection-nick server)
724                           (murk-msg-src msg))))
725        (let ((channel (car (murk-msg-params msg))))
726          (murk-display-notice (murk-current-context) "Left channel " channel)
727          (murk-remove-context (list server channel))
728          (murk-render-prompt)))
729
730       ("PART"
731        (let* ((channel (car (murk-msg-params msg)))
732               (nick (murk-msg-src msg))
733               (ctx (murk-get-context server channel)))
734          (murk-del-context-user ctx nick)
735          (if murk-show-joins
736              (murk-display-notice ctx nick " left channel " channel
737                                   " on " server))))
738
739       ((and "NICK"
740             (guard (equal (murk-connection-nick server)
741                           (murk-msg-src msg))))
742        (let ((new-nick (car (murk-msg-params msg)))
743              (old-nick (murk-connection-nick server)))
744          (murk-set-connection-nick server new-nick)
745          (murk-rename-server-user server old-nick new-nick)
746          (murk-display-notice nil "Nick set to " new-nick " on " server)))
747
748       ("NICK"
749        (let ((old-nick (murk-msg-src msg))
750              (new-nick (car (murk-msg-params msg))))
751          (murk-display-notice nil old-nick " is now known as " new-nick
752                               " on " server)
753          (murk-rename-server-user server old-nick new-nick)))
754
755       ("TOPIC"
756        (let ((channel (car (murk-msg-params msg)))
757              (nick (murk-msg-src msg))
758              (topic (cadr (murk-msg-params msg))))
759          (murk-display-notice (murk-get-context server channel)
760                               nick " set the topic: " topic)))
761
762       ("QUIT"
763        (let ((nick (murk-msg-src msg))
764              (reason (mapconcat 'identity (murk-msg-params msg) " ")))
765          (murk-del-server-user server nick)
766          (if murk-show-joins
767              (murk-display-notice nil nick " quit: " reason))))
768
769       ("PRIVMSG"
770        (let* ((from (murk-msg-src msg))
771               (params (murk-msg-params msg))
772               (to (car params))
773               (text (cadr params)))
774          (pcase text
775            ("\01VERSION\01"
776             (let ((version-string (concat murk-version " - running on GNU Emacs " emacs-version)))
777               (murk-send-msg server
778                              (murk-msg nil nil "NOTICE"
779                                        (list from (concat "\01VERSION "
780                                                           version-string
781                                                           "\01")))))
782             (murk-display-notice nil "CTCP version request received from "
783                                  from " on " server))
784
785            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
786             (murk-send-msg server (murk-msg nil nil "NOTICE" (list from ping)))
787             (murk-display-notice nil "CTCP ping received from " from " on " server))
788
789            ("\01USERINFO\01"
790             (murk-display-notice nil "CTCP userinfo request from " from
791                                  " on " server " (no response sent)"))
792
793            ("\01CLIENTINFO\01"
794             (murk-display-notice nil "CTCP clientinfo request from " from
795                                  " on " server " (no response sent)"))
796
797            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
798             (murk-display-action server from to action-text))
799
800            (_
801             (murk-display-message server from to text)))))
802
803       (_
804        (murk-display-notice nil (murk-msg->string msg))))))
805
806 ;;; Commands
807 ;;
808
809 (defvar murk-command-table
810   '(("DEBUG" "Toggle debug mode on/off." murk-command-debug murk-boolean-completions)
811     ("HEADER" "Toggle display of header." murk-command-header murk-boolean-completions)
812     ("SHOWJOINS" "Toggles display of joins/parts." murk-command-showjoins murk-boolean-completions)
813     ("NETWORKS" "List known IRC networks." murk-command-networks)
814     ("CONNECT" "Connect to an IRC network." murk-command-connect murk-network-completions)
815     ("QUIT" "Disconnect from current network." murk-command-quit)
816     ("JOIN" "Join one or more channels." murk-command-join)
817     ("PART" "Leave channel." murk-command-part murk-context-completions)
818     ("NICK" "Change nick." murk-command-nick)
819     ("LIST" "Display details of one or more channels." murk-command-list)
820     ("TOPIC" "Set/query topic for current channel." murk-command-topic)
821     ("USERS" "List nicks of users in current context." murk-command-users)
822     ("MSG" "Send private message to user." murk-command-msg murk-nick-completions)
823     ("ME" "Display action." murk-command-me)
824     ("CLEAR" "Clear buffer text." murk-command-clear murk-context-completions)
825     ("HELP" "Display help on client commands." murk-command-help murk-help-completions))
826   "Table of commands explicitly supported by murk.")
827
828 (defun murk-boolean-completions ()
829   '("on" "off"))
830
831 (defun murk-network-completions ()
832   (mapcar (lambda (row) (car row)) murk-networks))
833
834 (defun murk-command-help (params)
835   (if params
836       (let* ((cmd-str (upcase (car params)))
837              (row (assoc cmd-str murk-command-table #'equal)))
838         (if row
839             (progn
840               (murk-display-notice nil "Help for \x02" cmd-str "\x02:")
841               (murk-display-notice nil "  " (elt row 1)))
842           (murk-display-notice nil "No such (client-interpreted) command.")))
843     (murk-display-notice nil "Client-interpreted commands:")
844     (dolist (row murk-command-table)
845       (murk-display-notice nil "  \x02" (elt row 0) "\x02: " (elt row 1)))
846     (murk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
847
848 (defun murk-command-debug (params)
849   (setq murk-debug 
850         (if params
851             (if (equal (upcase (car params)) "ON")
852                 t
853               nil)
854           (not murk-debug)))
855   (murk-display-notice nil "Debug mode now " (if murk-debug "on" "off") "."))
856
857 (defun murk-command-header (params)
858   (if
859       (if params
860           (equal (upcase (car params)) "ON")
861         (not header-line-format))
862       (progn
863         (murk-setup-header)
864         (murk-display-notice nil "Header enabled."))
865     (setq-local header-line-format nil)
866     (murk-display-notice nil "Header disabled.")))
867
868 (defun murk-command-showjoins (params)
869   (setq murk-show-joins 
870         (if params
871             (if (equal (upcase (car params)) "ON")
872                 t
873               nil)
874           (not murk-show-joins)))
875   (murk-display-notice nil "Joins/parts will now be "
876                        (if murk-show-joins "shown" "hidden") "."))
877
878 (defun murk-command-connect (params)
879   (if params
880       (let ((network (car params)))
881         (murk-display-notice nil "Attempting to connect to " network "...")
882         (murk-connect network))
883     (murk-display-notice nil "Usage: /connect <network>")))
884
885 (defun murk-command-networks (_params)
886   (murk-display-notice nil "Currently-known networks:")
887   (dolist (row murk-networks)
888     (seq-let (network server port &rest _others) row
889       (murk-display-notice nil "\t" network
890                            " [" server
891                            " " (number-to-string port) "]")))
892   (murk-display-notice nil "(Modify the `murk-networks' variable to add more.)"))
893
894 (defun murk-command-quit (params)
895   (let ((ctx (murk-current-context)))
896     (if (not ctx)
897         (murk-display-error "No current context")
898       (let ((quit-msg (if params (string-join params " ") murk-default-quit-msg)))
899         (murk-send-msg
900          (murk-context-server ctx)
901          (murk-msg nil nil "QUIT" quit-msg))))))
902
903 (defun murk-command-join (params)
904   (if params
905       (let ((server (murk-context-server (murk-current-context))))
906         (dolist (channel params)
907           (murk-send-msg server (murk-msg nil nil "JOIN" channel))))
908     (murk-display-notice nil "Usage: /join channel [channel2 ...]")))
909
910 (defun murk-command-part (params)
911   (let* ((server (murk-context-server (murk-current-context)))
912          (channel (if params
913                       (car params)
914                     (murk-context-channel (murk-current-context)))))
915     (if channel
916         (murk-send-msg server (murk-msg nil nil "PART" channel))
917       (murk-display-error "No current channel to leave"))))
918
919 (defun murk-command-nick (params)
920   (if params
921       (let ((new-nick (string-join params " "))
922             (ctx (murk-current-context)))
923         (if ctx
924             (murk-send-msg (murk-context-server ctx)
925                            (murk-msg nil nil "NICK" new-nick))
926           (murk-display-error "No current connection")))
927     (murk-display-notice nil "Usage: /nick <new-nick>")))
928
929 (defun murk-command-list (params)
930   (let ((ctx (murk-current-context)))
931     (if ctx
932         (if (not params)
933             (murk-display-notice nil "This command can generate lots of output. Use `/LIST -yes' if you really want this, or `/LIST <channel_regexp>' to reduce the output.")
934           (let ((server (murk-context-server ctx)))
935             (if (equal (upcase (car params)) "-YES")
936                 (murk-send-msg server (murk-msg nil nil "LIST"))
937               (murk-send-msg server (murk-msg nil nil "LIST"
938                                               (car params))))))
939       (murk-display-error "No current connection"))))
940
941 (defun murk-command-topic (params)
942   (let ((ctx (murk-current-context)))
943     (if (and ctx (not (murk-server-context-p ctx)))
944         (let ((server (murk-context-server ctx))
945               (channel (murk-context-channel ctx)))
946           (if params
947               (murk-send-msg server
948                              (murk-msg nil nil "TOPIC" channel
949                                        (string-join params " ")))
950             (murk-send-msg server
951                            (murk-msg nil nil "TOPIC" channel))))
952       (murk-display-notice nil "No current channel."))))
953
954 (defun murk-command-msg (params)
955   (let ((server (murk-context-server (murk-current-context))))
956     (if (and params (>= (length params) 2))
957         (let ((to (car params))
958               (text (string-join (cdr params) " ")))
959           (murk-send-msg server (murk-msg nil nil "PRIVMSG" to text))
960           (murk-display-message server
961                                 (murk-connection-nick server)
962                                 to text))
963       (murk-display-notice nil "Usage: /msg <nick> <message>"))))
964
965 (defun murk-command-me (params)
966   (let* ((ctx (murk-current-context))
967          (server (murk-context-server ctx)))
968     (if (and ctx (not (murk-server-context-p ctx)))
969         (if params
970             (let* ((channel (murk-context-channel ctx))
971                    (my-nick (murk-connection-nick server))
972                    (action (string-join params " "))
973                    (ctcp-text (concat "\01ACTION " action "\01")))
974               (murk-send-msg server
975                              (murk-msg nil nil "PRIVMSG"
976                                        (list channel ctcp-text)))
977               (murk-display-action server my-nick channel action))
978           (murk-display-notice nil "Usage: /me <action>"))
979       (murk-display-notice nil "No current channel."))))
980
981 (defun murk-command-users (_params)
982   (let ((ctx (murk-current-context)))
983     (if (and ctx (not (murk-server-context-p ctx)))
984         (let ((channel (murk-context-channel ctx))
985               (server (murk-context-server ctx))
986               (users (murk-context-users ctx)))
987           (murk-display-notice ctx "Users in " channel " on " server ":")
988           (murk-display-notice ctx (string-join users " ")))
989       (murk-display-notice nil "No current channel."))))
990
991
992 ;;; Command entering
993 ;;
994
995 (defun murk-enter-string (string)
996   (if (string-prefix-p "/" string)
997       (pcase string
998         ((rx (: "/" (let cmd-str (+ (not whitespace)))
999                 (opt (+ whitespace)
1000                      (let params-str (+ anychar))
1001                      string-end)))
1002          (let ((command-row (assoc (upcase  cmd-str) murk-command-table #'equal))
1003                (params (if params-str
1004                            (split-string params-str nil t)
1005                          nil)))
1006            (if (and command-row (elt command-row 2))
1007                (funcall (elt command-row 2) params)
1008              (murk-send-msg
1009               (murk-context-server (murk-current-context))
1010               (murk-msg nil nil (upcase cmd-str) params)))))
1011         (_
1012          (murk-display-error "Badly formed command")))
1013     (unless (string-empty-p string)
1014       (let ((ctx (murk-current-context)))
1015         (if ctx
1016             (if (not (murk-server-context-p ctx))
1017                 (let ((server (murk-context-server ctx))
1018                       (channel (murk-context-channel ctx)))
1019                   (murk-send-msg server
1020                                  (murk-msg nil nil "PRIVMSG" channel string))
1021                   (murk-display-message server
1022                                         (murk-connection-nick server)
1023                                         channel string))
1024               (murk-display-error "No current channel"))
1025           (murk-display-error "No current context"))))))
1026
1027
1028 ;;; Command history
1029 ;;
1030
1031 (defvar murk-history nil
1032   "Commands and messages sent in current session.")
1033
1034 (defvar murk-history-index nil)
1035
1036 (defun murk-history-cycle (delta)
1037   (when murk-history
1038     (with-current-buffer "*murk*"
1039       (if murk-history-index
1040           (setq murk-history-index
1041                 (max 0
1042                      (min (- (length murk-history) 1)
1043                           (+ delta murk-history-index))))
1044         (setq murk-history-index 0))
1045       (delete-region murk-input-marker (point-max))
1046       (insert (elt murk-history murk-history-index)))))
1047
1048
1049 ;;; Interactive commands
1050 ;;
1051
1052 (defun murk-enter ()
1053   "Enter current contents of line after prompt."
1054   (interactive)
1055   (with-current-buffer "*murk*"
1056     (let ((line (buffer-substring murk-input-marker (point-max))))
1057       (push line murk-history)
1058       (setq murk-history-index nil)
1059       (let ((inhibit-read-only t))
1060         (delete-region murk-input-marker (point-max)))
1061       (murk-enter-string line))))
1062
1063 (defun murk-history-next ()
1064   (interactive)
1065   (murk-history-cycle -1))
1066
1067 (defun murk-history-prev ()
1068   (interactive)
1069   (murk-history-cycle +1))
1070
1071 (defun murk-cycle-contexts-forward ()
1072   (interactive)
1073   (murk-cycle-contexts)
1074   (murk-render-prompt))
1075
1076 (defun murk-cycle-contexts-reverse ()
1077   (interactive)
1078   (murk-cycle-contexts t)
1079   (murk-render-prompt))
1080
1081 (defun murk-complete-input ()
1082   (interactive)
1083   (let ((completion-ignore-case t))
1084     (when (>= (point) murk-input-marker)
1085       (pcase (buffer-substring murk-input-marker (point))
1086         ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
1087          (let ((space-idx (save-excursion
1088                             (re-search-backward " " murk-input-marker t)))
1089                (table-row (assoc (upcase cmd-str) murk-command-table #'equal)))
1090            (if (and table-row (elt table-row 3))
1091                (let* ((completions-nospace (funcall (elt table-row 3)))
1092                       (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
1093                  (completion-in-region (+ 1 space-idx) (point) completions)))))
1094         ((rx (: "/" (* (not whitespace)) string-end))
1095          (message (buffer-substring murk-input-marker (point)))
1096          (completion-in-region murk-input-marker (point)
1097                                (mapcar (lambda (row) (concat "/" (car row) " "))
1098                                        murk-command-table)))
1099         (_
1100          (let* ((end (max murk-input-marker (point)))
1101                 (space-idx (save-excursion
1102                              (re-search-backward " " murk-input-marker t)))
1103                 (start (if space-idx (+ 1 space-idx) murk-input-marker)))
1104            (unless (string-prefix-p "/" (buffer-substring start end))
1105              (let* ((users (murk-context-users (murk-current-context)))
1106                     (users-no@ (mapcar
1107                                 (lambda (u) (car (split-string u "@" t)))
1108                                 users)))
1109                (completion-in-region start end users-no@)))))))))
1110
1111 ;;; Mode
1112 ;;
1113
1114 (defvar murk-mode-map
1115   (let ((map (make-sparse-keymap)))
1116     (define-key map (kbd "RET") 'murk-enter)
1117     (define-key map (kbd "TAB") 'murk-complete-input)
1118     (define-key map (kbd "<C-up>") 'murk-history-prev)
1119     (define-key map (kbd "<C-down>") 'murk-history-next)
1120     (define-key map (kbd "<C-tab>") 'murk-cycle-contexts-forward)
1121     (define-key map (kbd "<C-S-iso-lefttab>") 'murk-cycle-contexts-reverse)
1122     (define-key map (kbd "<C-S-tab>") 'murk-cycle-contexts-reverse)
1123     (when (fboundp 'evil-define-key*)
1124       (evil-define-key* 'motion map
1125         (kbd "TAB") 'murk-complete-input))
1126     map))
1127
1128 (define-derived-mode murk-mode text-mode "murk"
1129   "Major mode for murk.")
1130
1131 (when (fboundp 'evil-set-initial-state)
1132   (evil-set-initial-state 'murk-mode 'insert))
1133
1134 ;;; Main start procedure
1135 ;;
1136
1137 (defun murk ()
1138   "Start murk or just switch to the murk buffer if one already exists."
1139   (interactive)
1140   (if (get-buffer "*murk*")
1141       (switch-to-buffer "*murk*")
1142     (switch-to-buffer "*murk*")
1143     (murk-mode)
1144     (murk-setup-buffer))
1145   "Started murk.")
1146
1147 ;;; murk.el ends here