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