1 ;;; MURK --- Multiserver Unibuffer iRc Klient -*- lexical-binding:t -*-
3 ;; Copyright (C) 2024 plugd
5 ;; Author: plugd <plugd@thelambdalab.xyz>
6 ;; Created: 11 May 2024
9 ;; Homepage: http://thelambdalab.xyz/murk
10 ;; Package-Requires: ((emacs "26"))
12 ;; This file is not part of GNU Emacs.
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.
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.
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/>.
37 "Multiserver Unibuffer iRc Klient"
40 (defcustom murk-default-nick "plugd"
43 (defcustom murk-default-quit-msg "Bye"
44 "Default quit message when none supplied.")
46 (defcustom murk-networks
47 '(("debug" "localhost" 6667 :notls)
48 ("libera" "irc.libera.chat" 6697)
49 ("tilde" "tilde.chat" 6697))
52 (defcustom murk-display-header t
53 "If non-nil, use buffer header to display information on current host and channel.")
60 '((t :inherit default))
61 "Face used for murk text.")
64 '((t :inherit font-lock-keyword-face))
65 "Face used for the prompt.")
68 '((t :inherit murk-context))
69 "Face used for the context name in the prompt.")
72 '((t :inherit shadow))
73 "Face used for faded murk text.")
75 (defface murk-timestamp
76 '((t :inherit shadow))
77 "Face used for timestamps.")
81 "Face used for murk error text.")
84 '((t :inherit warning))
85 "Face used for murk notice text.")
91 (defvar murk-version "Murk v0.0"
92 "Value of this string is used in response to CTCP version queries.")
94 (defvar murk-notice-prefix "-!-")
95 (defvar murk-error-prefix "!!!")
96 (defvar murk-prompt-string ">")
98 (defvar murk-debug nil
99 "If non-nil, enable debug mode.")
102 ;;; Utility procedures
105 (defun murk--filtered-join (&rest args)
106 (string-join (seq-filter (lambda (el) el) args) " "))
108 (defun murk--as-string (obj)
110 (with-output-to-string (princ obj))
114 ;;; Network processes
117 (defvar murk-connection-table nil
118 "An alist associating servers to connection information.
119 This includes the process and the response string.")
121 (defun murk-connection-process (server)
122 (elt (assoc server murk-connection-table) 1))
124 (defun murk-connection-nick (server)
125 (elt (assoc server murk-connection-table) 2))
127 (defun murk-set-connection-nick (server nick)
128 (setf (elt (assoc server murk-connection-table) 2) nick))
130 (defun murk-connection-response (server)
131 (elt (assoc server murk-connection-table) 3))
133 (defun murk-set-connection-response (server string)
134 (setf (elt (assoc server murk-connection-table) 3) string))
136 (defun murk-connection-new (server process nick)
137 (add-to-list 'murk-connection-table
138 (list server process nick "")))
140 (defun murk-connection-remove (server)
141 (setq murk-connection-table (assoc-delete-all server murk-connection-table)))
143 (defun murk-make-server-filter (server)
144 (lambda (proc string)
145 (dolist (line (split-string (concat (murk-connection-response server) string)
147 (if (string-suffix-p "\r" line)
148 (murk-eval-msg-string server (string-trim line))
149 (murk-set-connection-response server line)))))
151 (defun murk-make-server-sentinel (server)
152 (lambda (proc string)
153 (unless (equal "open" (string-trim string))
154 (murk-display-error "Disconnected from server.")
155 (murk-connection-remove server)
156 (murk-remove-server-contexts server)
157 (murk-render-prompt))))
159 (defun murk-start-process (server)
160 (let* ((row (assoc server murk-networks))
163 (flags (seq-drop row 3)))
164 (make-network-process :name (concat "murk-" server)
168 :filter (murk-make-server-filter server)
169 :sentinel (murk-make-server-sentinel server)
171 :tls-parameters (if (memq :notls flags)
173 (cons 'gnutls-x509pki
174 (gnutls-boot-parameters
175 :type 'gnutls-x509pki
179 (defvar murk-ping-period 60)
181 ;; IDEA: Have a single ping timer which pings all connected hosts
183 (defun murk-connect (server)
184 (if (assoc server murk-connection-table)
185 (murk-display-error "Already connected to this network.")
186 (if (not (assoc server murk-networks))
187 (murk-display-error "Network '" server "' is unknown.")
188 (let ((proc (murk-start-process server)))
189 (murk-connection-new server proc murk-default-nick))
190 (murk-send-msg server (murk-msg nil nil "USER" murk-default-nick 0 "*" murk-default-nick))
191 (murk-send-msg server (murk-msg nil nil "NICK" murk-default-nick))
192 (murk-add-context (list server))
193 (murk-render-prompt))))
195 (defun murk-send-msg (server msg)
197 (murk-display-string nil nil (murk-msg->string msg)))
198 (let ((proc (murk-connection-process server)))
199 (if (and proc (eq (process-status proc) 'open))
200 (process-send-string proc (concat (murk-msg->string msg) "\r\n"))
201 (murk-display-error "No server connection established."))))
207 (defun murk-msg (tags src cmd &rest params)
208 (list (murk--as-string tags)
209 (murk--as-string src)
210 (upcase (murk--as-string cmd))
211 (mapcar #'murk--as-string
212 (if (and params (listp (elt params 0)))
216 (defun murk-msg-tags (msg) (elt msg 0))
217 (defun murk-msg-src (msg) (elt msg 1))
218 (defun murk-msg-cmd (msg) (elt msg 2))
219 (defun murk-msg-params (msg) (elt msg 3))
220 (defun murk-msg-trail (msg)
221 (let ((params (murk-msg-params msg)))
223 (elt params (- (length params) 1)))))
225 (defvar murk-msg-regex
227 (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
229 (opt (: ":" (: (group (* (not (any space "!" "@"))))
230 (* (not (any space)))))
232 (group (: (* (not whitespace))))
234 (opt (group (+ not-newline))))
235 "Regex used to parse IRC messages.
236 Note that this regex is incomplete. Noteably, we discard the non-nick
237 portion of the source component of the message, as mURK doesn't use this.")
239 (defun murk-string->msg (string)
240 (if (string-match murk-msg-regex string)
241 (let* ((tags (match-string 1 string))
242 (src (match-string 2 string))
243 (cmd (upcase (match-string 3 string)))
244 (params-str (match-string 4 string))
247 (let* ((idx (cl-search ":" params-str))
248 (l (split-string (string-trim (substring params-str 0 idx))))
249 (r (if idx (list (substring params-str (+ 1 idx))) nil)))
252 (apply #'murk-msg (append (list tags src cmd) params)))
253 (error "Failed to parse string " string)))
255 (defun murk-msg->string (msg)
256 (let ((tags (murk-msg-tags msg))
257 (src (murk-msg-src msg))
258 (cmd (murk-msg-cmd msg))
259 (params (murk-msg-params msg)))
261 (if tags (concat "@" tags) nil)
262 (if src (concat ":" src) nil)
264 (if (> (length params) 1)
265 (string-join (seq-take params (- (length params) 1)) " ")
267 (if (> (length params) 0)
268 (concat ":" (elt params (- (length params) 1)))
272 ;;; Contexts and Servers
275 ;; A context is a list (server name ...) where name is a string
276 ;; representing either a channel name or nick, and server is a symbol
277 ;; identifying the server.
279 ;; Each server has a special context (server nil) used for messages
280 ;; to/from the server itself.
282 (defvar murk-contexts nil
283 "List of currently-available contexts.
284 The head of this list is always the current context.")
286 (defun murk-current-context ()
287 "Returns the current context."
292 (defun murk-contexts-equal (c1 c2)
293 (if (murk-server-context-p c1)
294 (and (murk-server-context-p c2)
295 (equal (murk-context-server c1)
296 (murk-context-server c2)))
297 (and (not (murk-server-context-p c2))
298 (equal (seq-take c1 2)
301 (defun murk-context-server (ctx) (elt ctx 0))
302 (defun murk-context-name (ctx) (elt ctx 1))
303 (defun murk-server-context-p (ctx) (not (cdr ctx)))
305 (defun murk-add-context (ctx)
306 (add-to-list 'murk-contexts ctx))
308 (defun murk-remove-context (ctx)
312 (murk-contexts-equal this-ctx ctx))
315 (defun murk-remove-server-contexts (server)
317 (assoc-delete-all server murk-contexts)))
319 (defun murk-context->string (ctx)
320 (if (murk-server-context-p ctx)
321 (concat "[" (murk-context-server ctx) "]")
322 (concat (murk-context-name ctx) "@"
323 (murk-context-server ctx))))
329 (defun murk-render-prompt ()
330 (with-current-buffer "*murk*"
331 (let ((update-point (= murk-input-marker (point)))
332 (update-window-points (mapcar (lambda (w)
333 (list (= (window-point w) murk-input-marker)
335 (get-buffer-window-list nil nil t))))
337 (set-marker-insertion-type murk-prompt-marker nil)
338 (set-marker-insertion-type murk-input-marker t)
339 (let ((inhibit-read-only t))
340 (delete-region murk-prompt-marker murk-input-marker)
341 (goto-char murk-prompt-marker)
343 (propertize (let ((ctx (murk-current-context)))
345 (murk-context->string ctx)
349 (propertize murk-prompt-string
352 (propertize " " ; Need this to be separate to mark it as rear-nonsticky
355 (set-marker-insertion-type murk-input-marker nil))
357 (goto-char murk-input-marker))
358 (dolist (v update-window-points)
360 (set-window-point (cadr v) murk-input-marker))))))
362 (defvar murk-prompt-marker nil
363 "Marker for prompt position in murk buffer.")
365 (defvar murk-input-marker nil
366 "Marker for prompt position in murk buffer.")
368 (defun murk-setup-header ()
372 (defun murk-setup-buffer ()
373 (with-current-buffer (get-buffer-create "*murk*")
374 (setq-local scroll-conservatively 1)
375 (setq-local buffer-invisibility-spec nil)
376 (if (markerp murk-prompt-marker)
377 (set-marker murk-prompt-marker (point-max))
378 (setq murk-prompt-marker (point-max-marker)))
379 (if (markerp murk-input-marker)
380 (set-marker murk-input-marker (point-max))
381 (setq murk-input-marker (point-max-marker)))
382 (goto-char (point-max))
384 (if murk-display-header
385 (murk-setup-header))))
387 (defun murk-clear-buffer ()
388 "Completely erase all non-prompt and non-input text from murk buffer."
389 (with-current-buffer "*murk*"
390 (let ((inhibit-read-only t))
391 (delete-region (point-min) murk-prompt-marker))))
394 ;;; Output formatting and highlighting
397 (defun murk--fill-strings (col indent &rest strings)
399 (setq buffer-invisibility-spec nil)
400 (let ((fill-column col)
401 (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
402 (apply #'insert strings)
403 (fill-region (point-min) (point-max) nil t)
406 (defun murk-display-string (context prefix &rest strings)
407 (with-current-buffer "*murk*"
409 (goto-char murk-prompt-marker)
410 (let* ((inhibit-read-only t)
411 (old-pos (marker-position murk-prompt-marker))
412 (padded-timestamp (concat (format-time-string "%H:%M ")))
413 (padded-prefix (if prefix (concat prefix " ") ""))
414 (context-atom (if context (intern (murk-context->string context)) nil)))
415 (insert-before-markers
418 (+ (length padded-timestamp)
419 (length padded-prefix))
420 (propertize padded-timestamp
421 'face 'murk-timestamp
424 'invisible context-atom)
425 (propertize padded-prefix
428 'invisible context-atom)
430 (propertize (concat (apply #'murk-buttonify-urls strings) "\n")
433 'invisible context-atom)))))))
434 (murk-scroll-windows-to-last-line))
436 (defun murk-display-notice (context &rest notices)
439 (propertize murk-notice-prefix 'face 'murk-notice)
440 (apply #'concat notices)))
442 (defun murk-display-error (&rest messages)
445 (propertize murk-error-prefix 'face 'murk-error)
446 (apply #'concat messages)))
448 (defun murk--start-of-final-line ()
449 (with-current-buffer "*murk*"
451 (goto-char (point-max))
452 (line-beginning-position))))
454 (defun murk-scroll-windows-to-last-line ()
455 (with-current-buffer "*murk*"
456 (dolist (window (get-buffer-window-list))
457 (if (>= (window-point window) (murk--start-of-final-line))
458 (with-selected-window window
463 (defconst murk-url-regex
467 (group (or (+ (any alnum "." "-"))
468 (+ (any alnum ":"))))
469 (opt (group (: ":" (+ digit))))
472 (* (any alnum "-/.,#:%=&_?~@+"))
473 (any alnum "-/#:%=&_~@+")))))))
474 "Imperfect regex used to find URLs in plain text.")
476 (defun murk-click-url (button)
477 (browse-url (button-get button 'url)))
479 (defun murk-buttonify-urls (&rest strings)
480 "Turn substrings which look like urls in STRING into clickable buttons."
482 (apply #'insert strings)
483 (goto-char (point-min))
484 (while (re-search-forward murk-url-regex nil t)
485 (let ((url (match-string 0)))
486 (make-text-button (match-beginning 0)
488 'action #'murk-click-url
492 'help-echo "Open URL in browser.")))
495 (defun murk-add-formatting (string)
498 (goto-char (point-min))
503 (prev-point (point)))
504 (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
505 (: "\x03" (+ digit) (opt "," (* digit)))))
507 (let ((beg (+ (match-beginning 0) 1)))
509 (add-face-text-property prev-point beg '(:weight bold)))
511 (add-face-text-property prev-point beg '(:slant italic)))
513 (add-face-text-property prev-point beg '(:underline t)))
515 (add-face-text-property prev-point beg '(:strike-through t)))
516 (pcase (match-string 0)
517 ("\x02" (setq bold (not bold)))
518 ("\x1D" (setq italics (not italics)))
519 ("\x1F" (setq underline (not underline)))
520 ("\x1E" (setq strikethrough (not strikethrough)))
525 (setq strikethrough nil))
527 (delete-region (match-beginning 0) (match-end 0))
528 (setq prev-point (point)))))
532 ;;; Message evaluation
535 (defun murk-eval-msg-string (server string)
537 (murk-display-string nil nil string))
538 (let* ((msg (murk-string->msg string)))
539 (pcase (murk-msg-cmd msg)
541 (murk-send-msg server
542 (murk-msg nil nil "PONG" (murk-msg-params msg))))
547 (let* ((params (murk-msg-params msg))
548 (nick (elt params 0))
549 (text (string-join (seq-drop params 1) " ")))
550 (murk-set-connection-nick server nick)
551 (murk-display-notice nil text)))
553 ((rx (= 3 (any digit)))
554 (murk-display-notice nil (mapconcat 'identity (cdr (murk-msg-params msg)) " ")))
557 (guard (equal (murk-connection-nick server)
558 (murk-msg-src msg))))
559 (let ((channel (car (murk-msg-params msg))))
560 (murk-add-context (list server channel))
561 (murk-display-notice (murk-current-context)
562 "Joining channel " channel " on " server)
563 (murk-render-prompt)))
566 (guard (equal (murk-connection-nick server)
567 (murk-msg-src msg))))
568 (let ((channel (car (murk-msg-params msg))))
569 (murk-display-notice (murk-current-context) "Left channel " channel)
570 (murk-remove-context (list server channel))
571 (murk-render-prompt)))
574 (let ((nick (murk-msg-src msg))
575 (reason (mapconcat 'identity (murk-msg-params msg) " ")))
578 (murk-display-notice nil nick " quit: " reason))))
581 (murk-display-notice nil (murk-msg->string msg))))))
586 (defvar murk-command-table
587 '(("DEBUG" "Toggle debug mode on/off." murk-command-debug murk-boolean-completions)
588 ("HEADER" "Toggle display of header." murk-command-header murk-boolean-completions)
589 ("NETWORKS" "List known IRC networks." murk-command-networks)
590 ("CONNECT" "Connect to an IRC network." murk-command-connect murk-network-completions)
591 ("QUIT" "Disconnect from current network." murk-command-quit)
592 ("JOIN" "Join one or more channels." murk-command-join)
593 ("PART" "Leave channel." murk-command-part murk-context-completions)
594 ("NICK" "Change nick." murk-command-nick)
595 ("MSG" "Send private message to user." murk-command-msg murk-nick-completions)
596 ("CLEAR" "Clear buffer text." murk-command-clear murk-context-completions)
597 ("HELP" "Display help on client commands." murk-command-help murk-help-completions))
598 "Table of commands explicitly supported by murk.")
600 (defun murk-boolean-completions ()
603 (defun murk-network-completions ()
604 (mapcar (lambda (row) (car row)) murk-networks))
606 (defun murk-command-help (params)
608 (let* ((cmd-str (upcase (car params)))
609 (row (assoc cmd-str murk-command-table #'equal)))
612 (murk-display-notice nil "Help for \x02" cmd-str "\x02:")
613 (murk-display-notice nil " " (elt row 1)))
614 (murk-display-notice nil "No such (client-interpreted) command.")))
615 (murk-display-notice nil "Client-interpreted commands:")
616 (dolist (row murk-command-table)
617 (murk-display-notice nil " \x02" (elt row 0) "\x02: " (elt row 1)))
618 (murk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
620 (defun murk-command-debug (params)
623 (if (equal (upcase (car params)) "ON")
627 (murk-display-notice nil "Debug mode now " (if murk-debug "on" "off") "."))
629 (defun murk-command-clear (params)
632 (dolist (context params)
633 (murk-clear-context context))))
635 (defun murk-command-connect (params)
637 (let ((network (car params)))
638 (murk-display-notice nil "Attempting to connect to " network "...")
639 (murk-connect network))
640 (murk-display-notice nil "Usage: /connect <network>")))
642 (defun murk-command-networks (params)
643 (murk-display-notice nil "Currently-known networks:")
644 (dolist (row murk-networks)
645 (seq-let (network server port &rest others) row
646 (murk-display-notice nil "\t" network
648 " " (number-to-string port) "]")))
649 (murk-display-notice nil "(Modify the `murk-networks' variable to add more.)"))
651 (defun murk-command-quit (params)
652 (let ((ctx (murk-current-context)))
654 (murk-display-error "No current context.")
655 (let ((quit-msg (if params (string-join params " ") murk-default-quit-msg)))
657 (murk-context-server ctx)
658 (murk-msg nil nil "QUIT" quit-msg))))))
660 (defun murk-command-join (params)
662 (let ((server (murk-context-server (murk-current-context))))
663 (dolist (channel params)
664 (murk-send-msg server (murk-msg nil nil "JOIN" channel))))
665 (murk-display-notice nil "Usage: /join channel [channel2 ...]")))
667 (defun murk-command-part (params)
668 (let* ((server (murk-context-server (murk-current-context)))
671 (murk-context-name (murk-current-context)))))
673 (murk-send-msg server (murk-msg nil nil "PART" channel))
674 (murk-display-error "No current channel to leave."))))
680 (defun murk-enter-string (string)
681 (if (string-prefix-p "/" string)
683 ((rx (: "/" (let cmd-str (+ (not whitespace)))
685 (let params-str (+ anychar))
687 (let ((command-row (assoc (upcase cmd-str) murk-command-table #'equal))
688 (params (if params-str
689 (split-string params-str nil t)
691 (if (and command-row (elt command-row 2))
692 (funcall (elt command-row 2) params)
694 (murk-context-server (murk-current-context))
695 (murk-msg nil nil (upcase cmd-str) params)))))
697 (murk-display-error "Badly formed command.")))
698 (unless (string-empty-p string)
699 (if (murk-current-context)
701 (murk-send-msg server
702 (murk-msg nil nil "PRIVMSG"
703 (murk-context-name murk-current-context)
705 (murk-display-message murk-nick (murk-context->string (murk-current-context)) string))
706 (murk-display-error "No current context.")))))
712 (defvar murk-history nil
713 "Commands and messages sent in current session.")
715 (defvar murk-history-index nil)
717 (defun murk-history-cycle (delta)
719 (with-current-buffer "*murk*"
720 (if murk-history-index
721 (setq murk-history-index
723 (min (- (length murk-history) 1)
724 (+ delta murk-history-index))))
725 (setq murk-history-index 0))
726 (delete-region murk-input-marker (point-max))
727 (insert (elt murk-history murk-history-index)))))
730 ;;; Interactive commands
734 "Enter current contents of line after prompt."
736 (with-current-buffer "*murk*"
737 (let ((line (buffer-substring murk-input-marker (point-max))))
738 (push line murk-history)
739 (setq murk-history-index nil)
740 (let ((inhibit-read-only t))
741 (delete-region murk-input-marker (point-max)))
742 (murk-enter-string line))))
744 (defun murk-history-next ()
746 (murk-history-cycle -1))
748 (defun murk-history-prev ()
750 (murk-history-cycle +1))
752 (defun murk-complete-input ()
754 (let ((completion-ignore-case t))
755 (when (>= (point) murk-input-marker)
756 (pcase (buffer-substring murk-input-marker (point))
757 ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
758 (let ((space-idx (save-excursion
759 (re-search-backward " " murk-input-marker t)))
760 (table-row (assoc (upcase cmd-str) murk-command-table #'equal)))
761 (if (and table-row (elt table-row 3))
762 (let* ((completions-nospace (funcall (elt table-row 3)))
763 (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
764 (completion-in-region (+ 1 space-idx) (point) completions)))))
765 ((rx (: "/" (* (not whitespace)) string-end))
766 (message (buffer-substring murk-input-marker (point)))
767 (completion-in-region murk-input-marker (point)
768 (mapcar (lambda (row) (concat "/" (car row) " "))
769 murk-command-table)))
771 (let* ((end (max murk-input-marker (point)))
772 (space-idx (save-excursion
773 (re-search-backward " " murk-input-marker t)))
774 (start (if space-idx (+ 1 space-idx) murk-input-marker)))
775 (unless (string-prefix-p "/" (buffer-substring start end))
776 (let* ((users (murk-get-context-users murk-current-context))
778 (lambda (u) (car (split-string u "@" t)))
780 (completion-in-region start end users-no@)))))))))
785 (defvar murk-mode-map
786 (let ((map (make-sparse-keymap)))
787 (define-key map (kbd "RET") 'murk-enter)
788 (define-key map (kbd "TAB") 'murk-complete-input)
789 (define-key map (kbd "<C-up>") 'murk-history-prev)
790 (define-key map (kbd "<C-down>") 'murk-history-next)
791 (when (fboundp 'evil-define-key*)
792 (evil-define-key* 'motion map
793 (kbd "TAB") 'murk-complete-input))
796 (define-derived-mode murk-mode text-mode "murk"
797 "Major mode for murk.")
799 (when (fboundp 'evil-set-initial-state)
800 (evil-set-initial-state 'murk-mode 'insert))
802 ;;; Main start procedure
806 "Start murk or just switch to the murk buffer if one already exists."
808 (if (get-buffer "*murk*")
809 (switch-to-buffer "*murk*")
810 (switch-to-buffer "*murk*")
816 ;;; murk.el ends here