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