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-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.")
101 ;;; Utility procedures
104 (defun murk--filtered-join (&rest args)
105 (string-join (seq-filter (lambda (el) el) args) " "))
107 (defun murk--as-string (obj)
109 (with-output-to-string (princ obj))
112 ;;; Network processes
115 (defvar murk-connection-table nil
116 "An alist associating servers to connection information.
117 This includes the process and the response string.")
119 (defun murk-connection-process (server)
120 (elt (assoc server murk-connection-table) 1))
122 (defun murk-connection-response (server)
123 (elt (assoc server murk-connection-table) 2))
125 (defun murk-set-connection-response (server string)
126 (setf (elt (assoc server murk-connection-table) 2) string))
128 (defun murk-connection-close (server)
129 (setq murk-connection-table (assoc-delete-all server murk-connection-table)))
131 (defun murk-make-server-filter (server)
132 (lambda (proc string)
133 (dolist (line (split-string (concat (murk-connection-response server) string)
135 (if (string-suffix-p "\r" line)
136 (murk-eval-msg-string server (string-trim line))
137 (murk-set-connection-response server line)))))
139 (defun murk-make-server-sentinel (server)
140 (lambda (proc string)
141 (unless (equal "open" (string-trim string))
142 (murk-display-error "Disconnected from server.")
143 (murk-remove-server-contexts server)
145 (murk-connection-close server))))
147 (defun murk-start-process (server)
148 (let* ((row (assoc server murk-networks))
151 (flags (seq-drop row 3)))
152 (make-network-process :name (concat "murk-" server)
156 :filter (murk-make-server-filter server)
157 :sentinel (murk-make-server-sentinel server)
159 :tls-parameters (if (memq :notls flags)
161 (cons 'gnutls-x509pki
162 (gnutls-boot-parameters
163 :type 'gnutls-x509pki
167 (defvar murk-ping-period 60)
169 ;; IDEA: Have a single ping timer which pings all connected hosts
171 (defun murk-connect (server)
172 (if (assoc server murk-connection-table)
173 (murk-display-error "Already connected to this network.")
174 (if (not (assoc server murk-networks))
175 (murk-display-error "Network '" server "' is unknown.")
176 (let ((proc (murk-start-process server)))
177 (add-to-list 'murk-connection-table
178 (list server proc "")))
179 (murk-send-msg server (murk-msg nil nil "USER" murk-nick 0 "*" murk-nick))
180 (murk-send-msg server (murk-msg nil nil "NICK" murk-nick))
181 (murk-add-context (list server)))))
183 (defun murk-send-msg (server msg)
185 (murk-display-string nil nil (murk-msg->string msg)))
186 (let ((proc (murk-connection-process server)))
187 (if (and proc (eq (process-status proc) 'open))
188 (process-send-string proc (concat (murk-msg->string msg) "\r\n"))
189 (murk-display-error "No server connection established.")
190 (error "No server connection established"))))
195 (defun murk-msg (tags src cmd &rest params)
196 (list (murk--as-string tags)
197 (murk--as-string src)
198 (upcase (murk--as-string cmd))
199 (mapcar #'murk--as-string
200 (if (and params (listp (elt params 0)))
204 (defun murk-msg-tags (msg) (elt msg 0))
205 (defun murk-msg-src (msg) (elt msg 1))
206 (defun murk-msg-cmd (msg) (elt msg 2))
207 (defun murk-msg-params (msg) (elt msg 3))
208 (defun murk-msg-trail (msg)
209 (let ((params (murk-msg-params msg)))
211 (elt params (- (length params) 1)))))
213 (defvar murk-msg-regex
215 (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
217 (opt (: ":" (: (group (* (not (any space "!" "@"))))
218 (* (not (any space)))))
220 (group (: (* (not whitespace))))
222 (opt (group (+ not-newline))))
223 "Regex used to parse IRC messages.
224 Note that this regex is incomplete. Noteably, we discard the non-nick
225 portion of the source component of the message, as mURK doesn't use this.")
227 (defun murk-string->msg (string)
228 (if (string-match murk-msg-regex string)
229 (let* ((tags (match-string 1 string))
230 (src (match-string 2 string))
231 (cmd (upcase (match-string 3 string)))
232 (params-str (match-string 4 string))
235 (let* ((idx (cl-search ":" params-str))
236 (l (split-string (string-trim (substring params-str 0 idx))))
237 (r (if idx (list (substring params-str (+ 1 idx))) nil)))
240 (apply #'murk-msg (append (list tags src cmd) params)))
241 (error "Failed to parse string " string)))
243 (defun murk-msg->string (msg)
244 (let ((tags (murk-msg-tags msg))
245 (src (murk-msg-src msg))
246 (cmd (murk-msg-cmd msg))
247 (params (murk-msg-params msg)))
249 (if tags (concat "@" tags) nil)
250 (if src (concat ":" src) nil)
252 (if (> (length params) 1)
253 (string-join (seq-take params (- (length params) 1)) " ")
255 (if (> (length params) 0)
256 (concat ":" (elt params (- (length params) 1)))
260 ;;; Contexts and Servers
263 ;; A context is a list (server name ...) where name is a string
264 ;; representing either a channel name or nick, and server is a symbol
265 ;; identifying the server.
267 ;; Each server has a special context (server) used for messages
268 ;; to/from the server itself.
270 (defvar murk-contexts nil
271 "List of currently-available contexts.
272 The head of this list is always the current context.")
274 (defun murk-current-context ()
275 "Returns the current context."
280 (defun murk-context-server (ctx) (elt ctx 0))
281 (defun murk-context-name (ctx) (elt ctx 1))
283 (defun murk-add-context (ctx)
284 (add-to-list 'murk-contexts ctx))
286 (defun murk-remove-server-contexts (server)
288 (assoc-delete-all server murk-contexts)))
293 (defun murk-render-prompt ()
294 (with-current-buffer "*murk*"
295 (let ((update-point (= murk-input-marker (point)))
296 (update-window-points (mapcar (lambda (w)
297 (list (= (window-point w) murk-input-marker)
299 (get-buffer-window-list nil nil t))))
301 (set-marker-insertion-type murk-prompt-marker nil)
302 (set-marker-insertion-type murk-input-marker t)
303 (let ((inhibit-read-only t))
304 (delete-region murk-prompt-marker murk-input-marker)
305 (goto-char murk-prompt-marker)
307 (propertize (let ((ctx (murk-current-context)))
309 (concat (murk-context-name) "@" (murk-context-server ctx))
313 (propertize murk-prompt-string
316 (propertize " " ; Need this to be separate to mark it as rear-nonsticky
319 (set-marker-insertion-type murk-input-marker nil))
321 (goto-char murk-input-marker))
322 (dolist (v update-window-points)
324 (set-window-point (cadr v) murk-input-marker))))))
326 (defvar murk-prompt-marker nil
327 "Marker for prompt position in murk buffer.")
329 (defvar murk-input-marker nil
330 "Marker for prompt position in murk buffer.")
332 (defun murk-setup-header ()
336 (defun murk-setup-buffer ()
337 (with-current-buffer (get-buffer-create "*murk*")
338 (setq-local scroll-conservatively 1)
339 (setq-local buffer-invisibility-spec nil)
340 (if (markerp murk-prompt-marker)
341 (set-marker murk-prompt-marker (point-max))
342 (setq murk-prompt-marker (point-max-marker)))
343 (if (markerp murk-input-marker)
344 (set-marker murk-input-marker (point-max))
345 (setq murk-input-marker (point-max-marker)))
346 (goto-char (point-max))
348 (if murk-display-header
349 (murk-setup-header))))
351 (defun murk-clear-buffer ()
352 "Completely erase all non-prompt and non-input text from murk buffer."
353 (with-current-buffer "*murk*"
354 (let ((inhibit-read-only t))
355 (delete-region (point-min) murk-prompt-marker))))
358 ;;; Output formatting and highlighting
361 (defun murk--fill-strings (col indent &rest strings)
363 (setq buffer-invisibility-spec nil)
364 (let ((fill-column col)
365 (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
366 (apply #'insert strings)
367 (fill-region (point-min) (point-max) nil t)
370 (defun murk-context->string (context)
372 (concat (murk-context-name) "@" (murk-context-server context))
375 (defun murk-display-string (context prefix &rest strings)
376 (with-current-buffer "*murk*"
378 (goto-char murk-prompt-marker)
379 (let* ((inhibit-read-only t)
380 (old-pos (marker-position murk-prompt-marker))
381 (padded-timestamp (concat (format-time-string "%H:%M ")))
382 (padded-prefix (if prefix (concat prefix " ") ""))
383 (context-atom (if context (intern (murk-context->string context)) nil)))
384 (insert-before-markers
387 (+ (length padded-timestamp)
388 (length padded-prefix))
389 (propertize padded-timestamp
390 'face 'murk-timestamp
393 'invisible context-atom)
394 (propertize padded-prefix
397 'invisible context-atom)
399 (propertize (concat (apply #'murk-buttonify-urls strings) "\n")
402 'invisible context-atom)))))))
403 (murk-scroll-windows-to-last-line))
405 (defun murk-display-notice (context &rest notices)
408 (propertize murk-notice-prefix 'face 'murk-notice)
409 (apply #'concat notices)))
411 (defun murk-display-error (&rest messages)
414 (propertize murk-error-prefix 'face 'murk-error)
415 (apply #'concat messages)))
417 (defun murk--start-of-final-line ()
418 (with-current-buffer "*murk*"
420 (goto-char (point-max))
421 (line-beginning-position))))
423 (defun murk-scroll-windows-to-last-line ()
424 (with-current-buffer "*murk*"
425 (dolist (window (get-buffer-window-list))
426 (if (>= (window-point window) (murk--start-of-final-line))
427 (with-selected-window window
432 (defconst murk-url-regex
436 (group (or (+ (any alnum "." "-"))
437 (+ (any alnum ":"))))
438 (opt (group (: ":" (+ digit))))
441 (* (any alnum "-/.,#:%=&_?~@+"))
442 (any alnum "-/#:%=&_~@+")))))))
443 "Imperfect regex used to find URLs in plain text.")
445 (defun murk-click-url (button)
446 (browse-url (button-get button 'url)))
448 (defun murk-buttonify-urls (&rest strings)
449 "Turn substrings which look like urls in STRING into clickable buttons."
451 (apply #'insert strings)
452 (goto-char (point-min))
453 (while (re-search-forward murk-url-regex nil t)
454 (let ((url (match-string 0)))
455 (make-text-button (match-beginning 0)
457 'action #'murk-click-url
461 'help-echo "Open URL in browser.")))
464 (defun murk-add-formatting (string)
467 (goto-char (point-min))
472 (prev-point (point)))
473 (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
474 (: "\x03" (+ digit) (opt "," (* digit)))))
476 (let ((beg (+ (match-beginning 0) 1)))
478 (add-face-text-property prev-point beg '(:weight bold)))
480 (add-face-text-property prev-point beg '(:slant italic)))
482 (add-face-text-property prev-point beg '(:underline t)))
484 (add-face-text-property prev-point beg '(:strike-through t)))
485 (pcase (match-string 0)
486 ("\x02" (setq bold (not bold)))
487 ("\x1D" (setq italics (not italics)))
488 ("\x1F" (setq underline (not underline)))
489 ("\x1E" (setq strikethrough (not strikethrough)))
494 (setq strikethrough nil))
496 (delete-region (match-beginning 0) (match-end 0))
497 (setq prev-point (point)))))
501 ;;; Message evaluation
504 (defun murk-eval-msg-string (server string)
506 (murk-display-string nil nil string))
507 (let* ((msg (murk-string->msg string)))
508 (pcase (murk-msg-cmd msg)
510 (murk-send-msg server
511 (murk-msg nil nil "PONG" (murk-msg-params msg))))
516 (murk-display-notice nil (murk-msg->string msg))))))
521 (defvar murk-command-table
522 '(("DEBUG" "Toggle debug mode on/off." murk-command-debug murk-boolean-completions)
523 ("HEADER" "Toggle display of header." murk-command-header murk-boolean-completions)
524 ("CONNECT" "Connect to an IRC network." murk-command-connect murk-network-completions)
525 ("NETWORKS" "List known IRC networks." murk-command-networks)
526 ("QUIT" "Disconnect from current network." murk-command-quit)
527 ("NICK" "Change nick." murk-command-nick)
528 ("MSG" "Send private message to user." murk-command-msg murk-nick-completions)
529 ("CLEAR" "Clear buffer text." murk-command-clear murk-context-completions)
530 ("HELP" "Display help on client commands." murk-command-help murk-help-completions))
531 "Table of commands explicitly supported by murk.")
533 (defun murk-boolean-completions ()
536 (defun murk-network-completions ()
537 (mapcar (lambda (row) (car row)) murk-networks))
539 (defun murk-command-help (params)
541 (let* ((cmd-str (upcase (car params)))
542 (row (assoc cmd-str murk-command-table #'equal)))
545 (murk-display-notice nil "Help for \x02" cmd-str "\x02:")
546 (murk-display-notice nil " " (elt row 1)))
547 (murk-display-notice nil "No such (client-interpreted) command.")))
548 (murk-display-notice nil "Client-interpreted commands:")
549 (dolist (row murk-command-table)
550 (murk-display-notice nil " \x02" (elt row 0) "\x02: " (elt row 1)))
551 (murk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
553 (defun murk-command-debug (params)
556 (if (equal (upcase (car params)) "ON")
560 (murk-display-notice nil "Debug mode now " (if murk-debug "on" "off") "."))
562 (defun murk-command-clear (params)
565 (dolist (context params)
566 (murk-clear-context context))))
568 (defun murk-command-connect (params)
570 (let ((network (car params)))
571 (murk-display-notice nil "Attempting to connect to " network "...")
572 (murk-connect network))
573 (murk-display-notice nil "Usage: /connect <network>")))
575 (defun murk-command-networks (params)
576 (murk-display-notice nil "Currently-known networks:")
577 (dolist (row murk-networks)
578 (seq-let (network server port &rest others) row
579 (murk-display-notice nil "\t" network
581 " " (number-to-string port) "]")))
582 (murk-display-notice nil "(Modify the `murk-networks' variable to add more.)"))
584 (defun murk-command-quit (params)
585 (let ((ctx (murk-current-context)))
587 (murk-display-error "No current context.")
588 (let ((quit-msg (if params (string-join params " ") murk-default-quit-msg)))
590 (murk-context-server ctx)
591 (lurk-msg nil nil "QUIT" quit-msg))))))
596 (defun murk-enter-string (string)
597 (if (string-prefix-p "/" string)
599 ((rx (: "/" (let cmd-str (+ (not whitespace)))
601 (let params-str (+ anychar))
603 (let ((command-row (assoc (upcase cmd-str) murk-command-table #'equal))
604 (params (if params-str
605 (split-string params-str nil t)
607 (if (and command-row (elt command-row 2))
608 (funcall (elt command-row 2) params)
610 (murk-context-server (murk-current-context))
611 (murk-msg nil nil (upcase cmd-str) params)))))
613 (murk-display-error "Badly formed command.")))
614 (unless (string-empty-p string)
615 (if (murk-current-context)
617 (murk-send-msg server
618 (murk-msg nil nil "PRIVMSG"
619 (murk-context-name murk-current-context)
621 (murk-display-message murk-nick (murk-context->string (murk-current-context)) string))
622 (murk-display-error "No current context.")))))
628 (defvar murk-history nil
629 "Commands and messages sent in current session.")
631 (defvar murk-history-index nil)
633 (defun murk-history-cycle (delta)
635 (with-current-buffer "*murk*"
636 (if murk-history-index
637 (setq murk-history-index
639 (min (- (length murk-history) 1)
640 (+ delta murk-history-index))))
641 (setq murk-history-index 0))
642 (delete-region murk-input-marker (point-max))
643 (insert (elt murk-history murk-history-index)))))
646 ;;; Interactive commands
650 "Enter current contents of line after prompt."
652 (with-current-buffer "*murk*"
653 (let ((line (buffer-substring murk-input-marker (point-max))))
654 (push line murk-history)
655 (setq murk-history-index nil)
656 (let ((inhibit-read-only t))
657 (delete-region murk-input-marker (point-max)))
658 (murk-enter-string line))))
660 (defun murk-history-next ()
662 (murk-history-cycle -1))
664 (defun murk-history-prev ()
666 (murk-history-cycle +1))
668 (defun murk-complete-input ()
670 (let ((completion-ignore-case t))
671 (when (>= (point) murk-input-marker)
672 (pcase (buffer-substring murk-input-marker (point))
673 ((rx (: "/" (let cmd-str (+ (not whitespace))) (+ " ") (* (not whitespace)) string-end))
674 (let ((space-idx (save-excursion
675 (re-search-backward " " murk-input-marker t)))
676 (table-row (assoc (upcase cmd-str) murk-command-table #'equal)))
677 (if (and table-row (elt table-row 3))
678 (let* ((completions-nospace (funcall (elt table-row 3)))
679 (completions (mapcar (lambda (el) (concat el " ")) completions-nospace)))
680 (completion-in-region (+ 1 space-idx) (point) completions)))))
681 ((rx (: "/" (* (not whitespace)) string-end))
682 (message (buffer-substring murk-input-marker (point)))
683 (completion-in-region murk-input-marker (point)
684 (mapcar (lambda (row) (concat "/" (car row) " "))
685 murk-command-table)))
687 (let* ((end (max murk-input-marker (point)))
688 (space-idx (save-excursion
689 (re-search-backward " " murk-input-marker t)))
690 (start (if space-idx (+ 1 space-idx) murk-input-marker)))
691 (unless (string-prefix-p "/" (buffer-substring start end))
692 (let* ((users (murk-get-context-users murk-current-context))
694 (lambda (u) (car (split-string u "@" t)))
696 (completion-in-region start end users-no@)))))))))
701 (defvar murk-mode-map
702 (let ((map (make-sparse-keymap)))
703 (define-key map (kbd "RET") 'murk-enter)
704 (define-key map (kbd "TAB") 'murk-complete-input)
705 (define-key map (kbd "<C-up>") 'murk-history-prev)
706 (define-key map (kbd "<C-down>") 'murk-history-next)
707 (when (fboundp 'evil-define-key*)
708 (evil-define-key* 'motion map
709 (kbd "TAB") 'murk-complete-input))
712 (define-derived-mode murk-mode text-mode "murk"
713 "Major mode for murk.")
715 (when (fboundp 'evil-set-initial-state)
716 (evil-set-initial-state 'murk-mode 'insert))
718 ;;; Main start procedure
722 "Start murk or just switch to the murk buffer if one already exists."
724 (if (get-buffer "*murk*")
725 (switch-to-buffer "*murk*")
726 (switch-to-buffer "*murk*")
732 ;;; murk.el ends here