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