Joins/parts update context users.
[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" 6667 :notls)
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     (assoc 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 ;;; Buffer
371 ;;
372
373 (defvar murk-prompt-marker nil
374   "Marker for prompt position in murk buffer.")
375
376 (defvar murk-input-marker nil
377   "Marker for prompt position in murk buffer.")
378
379 (defun murk-render-prompt ()
380   (with-current-buffer "*murk*"
381     (let ((update-point (= murk-input-marker (point)))
382           (update-window-points (mapcar (lambda (w)
383                                           (list (= (window-point w) murk-input-marker)
384                                                 w))
385                                         (get-buffer-window-list nil nil t))))
386       (save-excursion
387         (set-marker-insertion-type murk-prompt-marker nil)
388         (set-marker-insertion-type murk-input-marker t)
389         (let ((inhibit-read-only t))
390           (delete-region murk-prompt-marker murk-input-marker)
391           (goto-char murk-prompt-marker)
392           (insert
393            (propertize (let ((ctx (murk-current-context)))
394                          (if ctx
395                              (murk-context->string ctx)
396                            ""))
397                        'face 'murk-context
398                        'read-only t)
399            (propertize murk-prompt-string
400                        'face 'murk-prompt
401                        'read-only t)
402            (propertize " " ; Need this to be separate to mark it as rear-nonsticky
403                        'read-only t
404                        'rear-nonsticky t)))
405         (set-marker-insertion-type murk-input-marker nil))
406       (if update-point
407           (goto-char murk-input-marker))
408       (dolist (v update-window-points)
409         (if (car v)
410             (set-window-point (cadr v) murk-input-marker))))))
411   
412 (defun murk-setup-header ()
413   (with-current-buffer "*murk*"
414     (setq-local header-line-format
415                 '((:eval
416                    (let* ((ctx (murk-current-context)))
417                      (if ctx
418                          (let ((server (murk-context-server ctx)))
419                            (concat
420                             "Network: " server ", "
421                             (if (murk-server-context-p ctx)
422                                 "Server"
423                               (concat
424                                "Channel: "
425                                (murk-context-channel ctx)
426                                " ("
427                                (number-to-string
428                                 (length (murk-context-users ctx)))
429                                ")"))))
430                        "No connection")))))))
431
432 (defun murk-setup-buffer ()
433   (with-current-buffer (get-buffer-create "*murk*")
434     (setq-local scroll-conservatively 1)
435     (setq-local buffer-invisibility-spec nil)
436     (if (markerp murk-prompt-marker)
437         (set-marker murk-prompt-marker (point-max))
438       (setq murk-prompt-marker (point-max-marker)))
439     (if (markerp murk-input-marker)
440         (set-marker murk-input-marker (point-max))
441       (setq murk-input-marker (point-max-marker)))
442     (goto-char (point-max))
443     (murk-render-prompt)
444     (if murk-display-header
445         (murk-setup-header))))
446
447 (defun murk-clear-buffer ()
448   "Completely erase all non-prompt and non-input text from murk buffer."
449   (with-current-buffer "*murk*"
450     (let ((inhibit-read-only t))
451       (delete-region (point-min) murk-prompt-marker))))
452
453
454 ;;; Output formatting and highlighting
455 ;;
456
457 (defun murk--fill-strings (col indent &rest strings)
458   (with-temp-buffer
459     (setq buffer-invisibility-spec nil)
460     (let ((fill-column col)
461           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
462       (apply #'insert strings)
463       (fill-region (point-min) (point-max) nil t)
464       (buffer-string))))
465
466 (defun murk-display-string (context prefix &rest strings)
467   (with-current-buffer "*murk*"
468     (save-excursion
469       (goto-char murk-prompt-marker)
470       (let* ((inhibit-read-only t)
471              (old-pos (marker-position murk-prompt-marker))
472              (padded-timestamp (concat (format-time-string "%H:%M ")))
473              (padded-prefix (if prefix (concat prefix " ") ""))
474              (context-atom (if context (intern (murk-context->string context)) nil)))
475         (insert-before-markers
476          (murk--fill-strings
477           80
478           (+ (length padded-timestamp)
479              (length padded-prefix))
480           (propertize padded-timestamp
481                       'face 'murk-timestamp
482                       'read-only t
483                       'context context
484                       'invisible context-atom)
485           (propertize padded-prefix
486                       'read-only t
487                       'context context
488                       'invisible context-atom)
489           (murk-add-formatting
490            (propertize (concat (apply #'murk-buttonify-urls strings) "\n")
491                        'read-only t
492                        'context context
493                        'invisible context-atom)))))))
494   (murk-scroll-windows-to-last-line))
495
496 (defun murk-display-message (server from to text)
497   (let ((context (if (string-prefix-p "#" to)
498                      (murk-get-context server to)
499                    (murk-get-context server))))
500     (murk-display-string
501      context
502      (if (murk-server-context-p context)
503          (concat "[" from " -> " to "]")
504        (concat (murk-context->string context) " <" from ">"))
505      text)))
506
507 (defun murk-display-notice (context &rest notices)
508   (murk-display-string
509    context
510    (propertize murk-notice-prefix 'face 'murk-notice)
511    (apply #'concat notices)))
512
513 (defun murk-display-error (&rest messages)
514   (murk-display-string
515    nil
516    (propertize murk-error-prefix 'face 'murk-error)
517    (apply #'concat messages)))
518
519 (defun murk--start-of-final-line ()
520   (with-current-buffer "*murk*"
521     (save-excursion
522       (goto-char (point-max))
523       (line-beginning-position))))
524
525 (defun murk-scroll-windows-to-last-line ()
526   (with-current-buffer "*murk*"
527     (dolist (window (get-buffer-window-list))
528       (if (>= (window-point window) (murk--start-of-final-line))
529           (with-selected-window window
530             (recenter -1))))))
531
532 (defconst murk-url-regex
533   (rx (:
534        (group (+ alpha))
535        "://"
536        (group (or (+ (any alnum "." "-"))
537                   (+ (any alnum ":"))))
538        (opt (group (: ":" (+ digit))))
539        (opt (group (: "/"
540                       (opt
541                        (* (any alnum "-/.,#:%=&_?~@+"))
542                        (any alnum "-/#:%=&_~@+")))))))
543   "Imperfect regex used to find URLs in plain text.")
544
545 (defun murk-click-url (button)
546   (browse-url (button-get button 'url)))
547
548 (defun murk-buttonify-urls (&rest strings)
549   "Turn substrings which look like urls in STRING into clickable buttons."
550   (with-temp-buffer
551     (apply #'insert strings)
552     (goto-char (point-min))
553     (while (re-search-forward murk-url-regex nil t)
554       (let ((url (match-string 0)))
555         (make-text-button (match-beginning 0)
556                           (match-end 0)
557                           'action #'murk-click-url
558                           'url url
559                           'follow-link t
560                           'face 'button
561                           'help-echo "Open URL in browser.")))
562     (buffer-string)))
563
564 (defun murk-add-formatting (string)
565   (with-temp-buffer
566     (insert string)
567     (goto-char (point-min))
568     (let ((bold nil)
569           (italics nil)
570           (underline nil)
571           (strikethrough nil)
572           (prev-point (point)))
573       (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
574                                         (: "\x03" (+ digit) (opt "," (* digit)))))
575                                 nil t)
576         (let ((beg (+ (match-beginning 0) 1)))
577           (if bold
578               (add-face-text-property prev-point beg '(:weight bold)))
579           (if italics
580               (add-face-text-property prev-point beg '(:slant italic)))
581           (if underline
582               (add-face-text-property prev-point beg '(:underline t)))
583           (if strikethrough
584               (add-face-text-property prev-point beg '(:strike-through t)))
585           (pcase (match-string 0)
586             ("\x02" (setq bold (not bold)))
587             ("\x1D" (setq italics (not italics)))
588             ("\x1F" (setq underline (not underline)))
589             ("\x1E" (setq strikethrough (not strikethrough)))
590             ("\x0F" ; Reset
591              (setq bold nil)
592              (setq italics nil)
593              (setq underline nil)
594              (setq strikethrough nil))
595             (_))
596           (delete-region (match-beginning 0) (match-end 0))
597           (setq prev-point (point)))))
598     (buffer-string)))
599
600
601 ;;; Message evaluation
602 ;;
603
604 (defun murk-eval-msg-string (server string)
605   (if murk-debug
606       (murk-display-string nil nil string))
607   (let* ((msg (murk-string->msg string)))
608     (pcase (murk-msg-cmd msg)
609       ("PING"
610        (murk-send-msg server
611         (murk-msg nil nil "PONG" (murk-msg-params msg))))
612
613       ("PONG")
614
615       ("001"
616        (let* ((params (murk-msg-params msg))
617               (nick (elt params 0))
618               (text (string-join (seq-drop params 1) " ")))
619          (murk-set-connection-nick server nick)
620          (murk-display-notice nil text)))
621
622       ("353" ; NAMEREPLY
623        (let* ((params (murk-msg-params msg))
624               (channel (elt params 2))
625               (names (split-string (elt params 3)))
626               (ctx (murk-get-context server channel)))
627          (if ctx
628              (murk-add-context-users ctx names)
629            (murk-display-notice nil "Users in " channel
630                                 ": " (string-join names " ")))))
631
632       ("366" ; ENDOFNAMES
633        (let* ((params (murk-msg-params msg))
634               (channel (elt params 1))
635               (ctx (murk-get-context server channel)))
636          (if ctx
637              (murk-display-notice
638               ctx
639               (murk--as-string (length (murk-context-users ctx)))
640               " users in " channel)
641            (murk-display-notice nil "End of " channel " names list."))))
642
643       ("331"
644        (let* ((params (murk-msg-params msg))
645               (channel (elt params 1))
646               (ctx (murk-get-context server channel)))
647          (murk-display-notice ctx "No topic set.")))
648
649       ("332"
650        (let* ((params (murk-msg-params msg))
651               (channel (elt params 1))
652               (topic (elt params 2))
653               (ctx (murk-get-context server channel)))
654          (murk-display-notice ctx "Topic: " topic)))
655
656       ((rx (= 3 (any digit)))
657        (murk-display-notice nil (mapconcat 'identity (cdr (murk-msg-params msg)) " ")))
658
659       ((and "JOIN"
660             (guard (equal (murk-connection-nick server)
661                           (murk-msg-src msg))))
662        (let ((channel (car (murk-msg-params msg))))
663          (murk-add-context (list server channel nil))
664          (murk-display-notice (murk-current-context)
665                               "Joining channel " channel " on " server)
666          (murk-render-prompt)))
667
668       ("JOIN"
669        (let* ((channel (car (murk-msg-params msg)))
670               (nick (murk-msg-src msg))
671               (ctx (murk-get-context server channel)))
672          (murk-add-context-users ctx (list nick))
673          (if murk-show-joins
674              (murk-display-notice ctx nick " joined channel " channel
675                                   " on " server))))
676
677       ((and "PART"
678             (guard (equal (murk-connection-nick server)
679                           (murk-msg-src msg))))
680        (let ((channel (car (murk-msg-params msg))))
681          (murk-display-notice (murk-current-context) "Left channel " channel)
682          (murk-remove-context (list server channel))
683          (murk-render-prompt)))
684
685       ("PART"
686        (let* ((channel (car (lurk-msg-params msg)))
687               (nick (lurk-msg-src msg))
688               (ctx (murk-get-context server channel)))
689          (murk-del-context-user ctx nick)
690          (if murk-show-joins
691              (murk-display-notice ctx nick " left channel " channel
692                                   " on " server))))
693
694       ("QUIT"
695        (let ((nick (murk-msg-src msg))
696              (reason (mapconcat 'identity (murk-msg-params msg) " ")))
697          (murk-del-user nick)
698          (if murk-show-joins
699              (murk-display-notice nil nick " quit: " reason))))
700
701       ("PRIVMSG"
702        (let* ((from (murk-msg-src msg))
703               (params (murk-msg-params msg))
704               (to (car params))
705               (text (cadr params)))
706          (pcase text
707            ("\01VERSION\01"
708             (let ((version-string (concat murk-version " - running on GNU Emacs " emacs-version)))
709               (murk-send-msg server
710                              (murk-msg nil nil "NOTICE"
711                                        (list from (concat "\01VERSION "
712                                                           version-string
713                                                           "\01")))))
714             (murk-display-notice nil "CTCP version request received from "
715                                  from " on " server))
716
717            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
718             (murk-send-msg server (murk-msg nil nil "NOTICE" (list from ping)))
719             (murk-display-notice nil "CTCP ping received from " from " on " server))
720
721            ("\01USERINFO\01"
722             (murk-display-notice nil "CTCP userinfo request from " from
723                                  " on " server " (no response sent)"))
724
725            ("\01CLIENTINFO\01"
726             (murk-display-notice nil "CTCP clientinfo request from " from
727                                  " on " server " (no response sent)"))
728
729            ((rx (: "\01ACTION " (let action-text (* (not "\01"))) "\01"))
730             (murk-display-action from to action-text))
731
732            (_
733             (murk-display-message server from to text)))))
734
735       (_
736        (murk-display-notice nil (murk-msg->string msg))))))
737
738 ;;; Commands
739 ;;
740
741 (defvar murk-command-table
742   '(("DEBUG" "Toggle debug mode on/off." murk-command-debug murk-boolean-completions)
743     ("HEADER" "Toggle display of header." murk-command-header murk-boolean-completions)
744     ("SHOWJOINS" "Toggles display of joins/parts." murk-command-showjoins murk-boolean-completions)
745     ("NETWORKS" "List known IRC networks." murk-command-networks)
746     ("CONNECT" "Connect to an IRC network." murk-command-connect murk-network-completions)
747     ("QUIT" "Disconnect from current network." murk-command-quit)
748     ("JOIN" "Join one or more channels." murk-command-join)
749     ("PART" "Leave channel." murk-command-part murk-context-completions)
750     ("NICK" "Change nick." murk-command-nick)
751     ("MSG" "Send private message to user." murk-command-msg murk-nick-completions)
752     ("CLEAR" "Clear buffer text." murk-command-clear murk-context-completions)
753     ("HELP" "Display help on client commands." murk-command-help murk-help-completions))
754   "Table of commands explicitly supported by murk.")
755
756 (defun murk-boolean-completions ()
757   '("on" "off"))
758
759 (defun murk-network-completions ()
760   (mapcar (lambda (row) (car row)) murk-networks))
761
762 (defun murk-command-help (params)
763   (if params
764       (let* ((cmd-str (upcase (car params)))
765              (row (assoc cmd-str murk-command-table #'equal)))
766         (if row
767             (progn
768               (murk-display-notice nil "Help for \x02" cmd-str "\x02:")
769               (murk-display-notice nil "  " (elt row 1)))
770           (murk-display-notice nil "No such (client-interpreted) command.")))
771     (murk-display-notice nil "Client-interpreted commands:")
772     (dolist (row murk-command-table)
773       (murk-display-notice nil "  \x02" (elt row 0) "\x02: " (elt row 1)))
774     (murk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
775
776 (defun murk-command-debug (params)
777   (setq murk-debug 
778         (if params
779             (if (equal (upcase (car params)) "ON")
780                 t
781               nil)
782           (not murk-debug)))
783   (murk-display-notice nil "Debug mode now " (if murk-debug "on" "off") "."))
784
785 (defun murk-command-header (params)
786   (if
787       (if params
788           (equal (upcase (car params)) "ON")
789         (not header-line-format))
790       (progn
791         (murk-setup-header)
792         (murk-display-notice nil "Header enabled."))
793     (setq-local header-line-format nil)
794     (murk-display-notice nil "Header disabled.")))
795
796 (defun murk-command-showjoins (params)
797   (setq murk-show-joins 
798         (if params
799             (if (equal (upcase (car params)) "ON")
800                 t
801               nil)
802           (not murk-show-joins)))
803   (murk-display-notice nil "Joins/parts will now be "
804                        (if murk-show-joins "shown" "hidden") "."))
805
806 (defun murk-command-clear (params)
807   (if (not params)
808       (murk-clear-buffer)
809     (dolist (context params)
810       (murk-clear-context context))))
811
812 (defun murk-command-connect (params)
813   (if params
814       (let ((network (car params)))
815         (murk-display-notice nil "Attempting to connect to " network "...")
816         (murk-connect network))
817     (murk-display-notice nil "Usage: /connect <network>")))
818
819 (defun murk-command-networks (_params)
820   (murk-display-notice nil "Currently-known networks:")
821   (dolist (row murk-networks)
822     (seq-let (network server port &rest _others) row
823       (murk-display-notice nil "\t" network
824                            " [" server
825                            " " (number-to-string port) "]")))
826   (murk-display-notice nil "(Modify the `murk-networks' variable to add more.)"))
827
828 (defun murk-command-quit (params)
829   (let ((ctx (murk-current-context)))
830     (if (not ctx)
831         (murk-display-error "No current context")
832       (let ((quit-msg (if params (string-join params " ") murk-default-quit-msg)))
833         (murk-send-msg
834          (murk-context-server ctx)
835          (murk-msg nil nil "QUIT" quit-msg))))))
836
837 (defun murk-command-join (params)
838   (if params
839       (let ((server (murk-context-server (murk-current-context))))
840         (dolist (channel params)
841           (murk-send-msg server (murk-msg nil nil "JOIN" channel))))
842     (murk-display-notice nil "Usage: /join channel [channel2 ...]")))
843
844 (defun murk-command-part (params)
845   (let* ((server (murk-context-server (murk-current-context)))
846          (channel (if params
847                       (car params)
848                     (murk-context-channel (murk-current-context)))))
849     (if channel
850         (murk-send-msg server (murk-msg nil nil "PART" channel))
851       (murk-display-error "No current channel to leave"))))
852
853 (defun murk-command-msg (params)
854   (let ((server (murk-context-server (murk-current-context))))
855     (if (and params (>= (length params) 2))
856         (let ((to (car params))
857               (text (string-join (cdr params) " ")))
858           (murk-send-msg server (murk-msg nil nil "PRIVMSG" to text))
859           (murk-display-message server
860                                 (murk-connection-nick server)
861                                 to text))
862       (murk-display-notice nil "Usage: /msg <nick> <message>"))))
863
864 ;;; Command entering
865 ;;
866
867 (defun murk-enter-string (string)
868   (if (string-prefix-p "/" string)
869       (pcase string
870         ((rx (: "/" (let cmd-str (+ (not whitespace)))
871                 (opt (+ whitespace)
872                      (let params-str (+ anychar))
873                      string-end)))
874          (let ((command-row (assoc (upcase  cmd-str) murk-command-table #'equal))
875                (params (if params-str
876                            (split-string params-str nil t)
877                          nil)))
878            (if (and command-row (elt command-row 2))
879                (funcall (elt command-row 2) params)
880              (murk-send-msg
881               (murk-context-server (murk-current-context))
882               (murk-msg nil nil (upcase cmd-str) params)))))
883         (_
884          (murk-display-error "Badly formed command")))
885     (unless (string-empty-p string)
886       (let ((ctx (murk-current-context)))
887         (if ctx
888             (if (not (murk-server-context-p ctx))
889                 (let ((server (murk-context-server ctx))
890                       (channel (murk-context-channel ctx)))
891                   (murk-send-msg server
892                                  (murk-msg nil nil "PRIVMSG" channel string))
893                   (murk-display-message server
894                                         (murk-connection-nick server)
895                                         channel string))
896               (murk-display-error "No current channel"))
897           (murk-display-error "No current context"))))))
898
899
900 ;;; Command history
901 ;;
902
903 (defvar murk-history nil
904   "Commands and messages sent in current session.")
905
906 (defvar murk-history-index nil)
907
908 (defun murk-history-cycle (delta)
909   (when murk-history
910     (with-current-buffer "*murk*"
911       (if murk-history-index
912           (setq murk-history-index
913                 (max 0
914                      (min (- (length murk-history) 1)
915                           (+ delta murk-history-index))))
916         (setq murk-history-index 0))
917       (delete-region murk-input-marker (point-max))
918       (insert (elt murk-history murk-history-index)))))
919
920
921 ;;; Interactive commands
922 ;;
923
924 (defun murk-enter ()
925   "Enter current contents of line after prompt."
926   (interactive)
927   (with-current-buffer "*murk*"
928     (let ((line (buffer-substring murk-input-marker (point-max))))
929       (push line murk-history)
930       (setq murk-history-index nil)
931       (let ((inhibit-read-only t))
932         (delete-region murk-input-marker (point-max)))
933       (murk-enter-string line))))
934
935 (defun murk-history-next ()
936   (interactive)
937   (murk-history-cycle -1))
938
939 (defun murk-history-prev ()
940   (interactive)
941   (murk-history-cycle +1))
942
943 (defun murk-cycle-contexts-forward ()
944   (interactive)
945   (murk-cycle-contexts)
946   (murk-render-prompt))
947
948 (defun murk-cycle-contexts-reverse ()
949   (interactive)
950   (murk-cycle-contexts t)
951   (murk-render-prompt))
952
953 (defun murk-complete-input ()
954   (interactive)
955   (let ((completion-ignore-case t))
956     (when (>= (point) murk-input-marker)
957       (pcase (buffer-substring murk-input-marker (point))
958         ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
959          (let ((space-idx (save-excursion
960                             (re-search-backward " " murk-input-marker t)))
961                (table-row (assoc (upcase cmd-str) murk-command-table #'equal)))
962            (if (and table-row (elt table-row 3))
963                (let* ((completions-nospace (funcall (elt table-row 3)))
964                       (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
965                  (completion-in-region (+ 1 space-idx) (point) completions)))))
966         ((rx (: "/" (* (not whitespace)) string-end))
967          (message (buffer-substring murk-input-marker (point)))
968          (completion-in-region murk-input-marker (point)
969                                (mapcar (lambda (row) (concat "/" (car row) " "))
970                                        murk-command-table)))
971         (_
972          (let* ((end (max murk-input-marker (point)))
973                 (space-idx (save-excursion
974                              (re-search-backward " " murk-input-marker t)))
975                 (start (if space-idx (+ 1 space-idx) murk-input-marker)))
976            (unless (string-prefix-p "/" (buffer-substring start end))
977              (let* ((users (murk-context-users (murk-current-context)))
978                     (users-no@ (mapcar
979                                 (lambda (u) (car (split-string u "@" t)))
980                                 users)))
981                (completion-in-region start end users-no@)))))))))
982
983 ;;; Mode
984 ;;
985
986 (defvar murk-mode-map
987   (let ((map (make-sparse-keymap)))
988     (define-key map (kbd "RET") 'murk-enter)
989     (define-key map (kbd "TAB") 'murk-complete-input)
990     (define-key map (kbd "<C-up>") 'murk-history-prev)
991     (define-key map (kbd "<C-down>") 'murk-history-next)
992     (define-key map (kbd "<C-tab>") 'murk-cycle-contexts-forward)
993     (define-key map (kbd "<C-S-iso-lefttab>") 'murk-cycle-contexts-reverse)
994     (define-key map (kbd "<C-S-tab>") 'murk-cycle-contexts-reverse)
995     (when (fboundp 'evil-define-key*)
996       (evil-define-key* 'motion map
997         (kbd "TAB") 'murk-complete-input))
998     map))
999
1000 (define-derived-mode murk-mode text-mode "murk"
1001   "Major mode for murk.")
1002
1003 (when (fboundp 'evil-set-initial-state)
1004   (evil-set-initial-state 'murk-mode 'insert))
1005
1006 ;;; Main start procedure
1007 ;;
1008
1009 (defun murk ()
1010   "Start murk or just switch to the murk buffer if one already exists."
1011   (interactive)
1012   (if (get-buffer "*murk*")
1013       (switch-to-buffer "*murk*")
1014     (switch-to-buffer "*murk*")
1015     (murk-mode)
1016     (murk-setup-buffer))
1017   "Started murk.")
1018
1019 ;;; murk.el ends here