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