Included repl.
[lurk.git] / murk.el
1 ;;; MURK --- 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 ;; Keywords: network
9 ;; Homepage: http://thelambdalab.xyz/murk
10 ;; Package-Requires: ((emacs "26"))
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 ;;; Code:
30
31 (provide 'murk)
32
33
34 ;;; Customizations
35
36 (defgroup murk nil
37   "Multiserver Unibuffer iRc Klient"
38   :group 'network)
39
40 (defcustom murk-nick "plugd"
41   "Default nick.")
42
43 (defcustom murk-default-quit-msg "Bye"
44   "Default quit message when none supplied.")
45
46 (defcustom murk-networks
47   '(("libera" "irc.libera.chat" 6697)
48     ("tilde" "tilde.chat" 6697))
49   "IRC networks.")
50
51 (defcustom murk-display-header t
52   "If non-nil, use buffer header to display information on current host and channel.")
53
54
55 ;;; Faces
56 ;;
57
58 (defface murk-text
59   '((t :inherit default))
60   "Face used for murk text.")
61
62 (defface murk-prompt
63   '((t :inherit font-lock-keyword-face))
64   "Face used for the prompt.")
65
66 (defface murk-context
67   '((t :inherit murk-context))
68   "Face used for the context name in the prompt.")
69
70 (defface murk-faded
71   '((t :inherit shadow))
72   "Face used for faded murk text.")
73
74 (defface murk-timestamp
75   '((t :inherit shadow))
76   "Face used for timestamps.")
77
78 (defface murk-error
79   '((t :inherit error))
80   "Face used for murk error text.")
81
82 (defface murk-notice
83   '((t :inherit warning))
84   "Face used for murk notice text.")
85
86
87 ;;; Global variables
88 ;;
89
90 (defvar murk-version "Murk v0.0"
91   "Value of this string is used in response to CTCP version queries.")
92
93 (defvar murk-notice-prefix "-!-")
94 (defvar murk-error-prefix "!!!")
95 (defvar murk-prompt-string ">")
96
97 (defvar murk-debug nil
98   "If non-nil, enable debug mode.")
99
100 ;;; Utility procedures
101 ;;
102
103 (defun murk--filtered-join (&rest args)
104   (string-join (seq-filter (lambda (el) el) args) " "))
105
106 (defun murk--as-string (obj)
107   (if obj
108       (with-output-to-string (princ obj))
109     nil))
110
111 ;;; Network processes
112 ;;
113
114 (defvar murk-connection-table nil
115   "An alist associating servers to connection information.
116 This includes the process and the response string.")
117
118 (defun murk-connection-process (server)
119   (elt (assoc server murk-connection-table) 1))
120
121 (defun murk-connection-response (server)
122   (elt (assoc server murk-connection-table) 2))
123
124 (defun murk-set-connection-response (server string)
125   (setf (elt (assoc server murk-connection-table) 2) string))
126
127 (defun murk-connection-close (server)
128   (setq murk-connection-table (assoc-delete-all server murk-connection-table)))
129
130 (defun murk-make-server-filter (server)
131   (lambda (proc string)
132     (dolist (line (split-string (concat (murk-connection-response server) string)
133                                 "\n"))
134       (if (string-suffix-p "\r" line)
135           (murk-eval-msg-string server (string-trim line))
136         (murk-set-connection-response line)))))
137
138 (defun murk-make-server-sentinel (server)
139   (lambda (proc string)
140     (unless (equal "open" (string-trim string))
141       (murk-display-error "Disconnected from server.")
142       (murk-remove-contexts-for-server server)
143       (murk-render-prompt)
144       (murk-connection-close server))))
145
146 (defun murk-start-process (server)
147   (let* ((row (assoc server murk-networks))
148          (host (elt row 1))
149          (port (elt row 2))
150          (flags (seq-drop row 3)))
151     (make-network-process :name (concat "murk-" server)
152                           :host host
153                           :service port
154                           :family nil
155                           :filter (murk-make-server-filter server)
156                           :sentinel (murk-make-server-sentinel server)
157                           :nowait nil
158                           :tls-parameters (if (memq :notls flags)
159                                               nil
160                                             (cons 'gnutls-x509pki
161                                                   (gnutls-boot-parameters
162                                                    :type 'gnutls-x509pki
163                                                    :hostname host)))
164                           :buffer "*murk*")))
165
166 (defvar murk-ping-period 60)
167
168 ;; IDEA: Have a single ping timer which pings all connected hosts
169
170 (defun murk-connect (server)
171   (if (assoc server murk-connection-table)
172       (murk-display-error "Already connected to this network.")
173     (if (not (assoc server murk-networks))
174         (murk-display-error "Network '" server "' is unknown.")
175       (let ((proc (murk-start-process server)))
176         (add-to-list murk-connection-table
177                      (list server proc "")))
178       (murk-send-msg server (murk-msg nil nil "USER" murk-nick 0 "*" murk-nick))
179       (murk-send-msg server (murk-msg nil nil "NICK" murk-nick)))))
180
181 (defun murk-send-msg (server msg)
182   (if murk-debug
183       (murk-display-string nil nil (murk-msg->string msg)))
184   (let ((proc (murk-connection-process server)))
185     (if (and proc (eq (process-status proc) 'open))
186         (process-send-string proc (concat (murk-msg->string msg) "\r\n"))
187       (murk-display-error "No server connection established.")
188       (error "No server connection established"))))
189
190 ;;; Server messages
191 ;;
192
193 (defun murk-msg (tags src cmd &rest params)
194   (list (murk--as-string tags)
195         (murk--as-string src)
196         (upcase (murk--as-string cmd))
197         (mapcar #'murk--as-string
198                 (if (and params (listp (elt params 0)))
199                     (elt params 0)
200                   params))))
201
202 (defun murk-msg-tags (msg) (elt msg 0))
203 (defun murk-msg-src (msg) (elt msg 1))
204 (defun murk-msg-cmd (msg) (elt msg 2))
205 (defun murk-msg-params (msg) (elt msg 3))
206 (defun murk-msg-trail (msg)
207   (let ((params (murk-msg-params msg)))
208     (if params
209         (elt params (- (length params) 1)))))
210
211 (defvar murk-msg-regex
212   (rx
213    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
214         (* whitespace))
215    (opt (: ":" (: (group (* (not (any space "!" "@"))))
216                   (* (not (any space)))))
217         (* whitespace))
218    (group (: (* (not whitespace))))
219    (* whitespace)
220    (opt (group (+ not-newline))))
221   "Regex used to parse IRC messages.
222 Note that this regex is incomplete.  Noteably, we discard the non-nick
223 portion of the source component of the message, as mURK doesn't use this.")
224
225 (defun murk-string->msg (string)
226   (if (string-match murk-msg-regex string)
227       (let* ((tags (match-string 1 string))
228              (src (match-string 2 string))
229              (cmd (upcase (match-string 3 string)))
230              (params-str (match-string 4 string))
231              (params
232               (if params-str
233                   (let* ((idx (cl-search ":" params-str))
234                          (l (split-string (string-trim (substring params-str 0 idx))))
235                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
236                     (append l r))
237                 nil)))
238         (apply #'murk-msg (append (list tags src cmd) params)))
239     (error "Failed to parse string " string)))
240
241 (defun murk-msg->string (msg)
242   (let ((tags (murk-msg-tags msg))
243         (src (murk-msg-src msg))
244         (cmd (murk-msg-cmd msg))
245         (params (murk-msg-params msg)))
246     (murk--filtered-join
247      (if tags (concat "@" tags) nil)
248      (if src (concat ":" src) nil)
249      cmd
250      (if (> (length params) 1)
251          (string-join (seq-take params (- (length params) 1)) " ")
252        nil)
253      (if (> (length params) 0)
254          (concat ":" (elt params (- (length params) 1)))
255        nil))))
256
257
258 ;;; Contexts and Servers
259 ;;
260
261 ;; A context is a list (server name ...) where name is a string
262 ;; representing either a channel name or nick, and server is a symbol
263 ;; identifying the server.
264 ;;
265 ;; Each server has a special context (server) used for messages
266 ;; to/from the server itself.
267
268 (defvar murk-contexts nil
269   "List of currently-available contexts.
270 The head of this list is always the current context.")
271
272 (defun murk-current-context ()
273   "Returns the current context."
274   (if murk-contexts
275       (car murk-contexts)
276     nil))
277
278 (defun murk-context-server (ctx) (elt ctx 0))
279 (defun murk-context-name (ctx) (elt ctx 1))
280
281 ;;; Buffer
282 ;;
283
284 (defun murk-render-prompt ()
285   (with-current-buffer "*murk*"
286     (let ((update-point (= murk-input-marker (point)))
287           (update-window-points (mapcar (lambda (w)
288                                           (list (= (window-point w) murk-input-marker)
289                                                 w))
290                                         (get-buffer-window-list nil nil t))))
291       (save-excursion
292         (set-marker-insertion-type murk-prompt-marker nil)
293         (set-marker-insertion-type murk-input-marker t)
294         (let ((inhibit-read-only t))
295           (delete-region murk-prompt-marker murk-input-marker)
296           (goto-char murk-prompt-marker)
297           (insert
298            (propertize (let ((ctx (murk-current-context)))
299                          (if ctx
300                            (concat (murk-context-name) "@" (murk-context-server ctx))
301                          ""))
302                        'face 'murk-context
303                        'read-only t)
304            (propertize murk-prompt-string
305                        'face 'murk-prompt
306                        'read-only t)
307            (propertize " " ; Need this to be separate to mark it as rear-nonsticky
308                        'read-only t
309                        'rear-nonsticky t)))
310         (set-marker-insertion-type murk-input-marker nil))
311       (if update-point
312           (goto-char murk-input-marker))
313       (dolist (v update-window-points)
314         (if (car v)
315             (set-window-point (cadr v) murk-input-marker))))))
316   
317 (defvar murk-prompt-marker nil
318   "Marker for prompt position in murk buffer.")
319
320 (defvar murk-input-marker nil
321   "Marker for prompt position in murk buffer.")
322
323 (defun murk-setup-header ()
324   ;; To do
325   )
326
327 (defun murk-setup-buffer ()
328   (with-current-buffer (get-buffer-create "*murk*")
329     (setq-local scroll-conservatively 1)
330     (setq-local buffer-invisibility-spec nil)
331     (if (markerp murk-prompt-marker)
332         (set-marker murk-prompt-marker (point-max))
333       (setq murk-prompt-marker (point-max-marker)))
334     (if (markerp murk-input-marker)
335         (set-marker murk-input-marker (point-max))
336       (setq murk-input-marker (point-max-marker)))
337     (goto-char (point-max))
338     (murk-render-prompt)
339     (if murk-display-header
340         (murk-setup-header))))
341
342 (defun murk-clear-buffer ()
343   "Completely erase all non-prompt and non-input text from murk buffer."
344   (with-current-buffer "*murk*"
345     (let ((inhibit-read-only t))
346       (delete-region (point-min) murk-prompt-marker))))
347
348
349 ;;; Output formatting and highlighting
350 ;;
351
352 (defun murk--fill-strings (col indent &rest strings)
353   (with-temp-buffer
354     (setq buffer-invisibility-spec nil)
355     (let ((fill-column col)
356           (adaptive-fill-regexp (rx-to-string `(= ,indent anychar))))
357       (apply #'insert strings)
358       (fill-region (point-min) (point-max) nil t)
359       (buffer-string))))
360
361 (defun murk-context->string (context)
362   (if context
363       (concat (murk-context-name) "@" (murk-context-server context))
364     nil))
365
366 (defun murk-display-string (context prefix &rest strings)
367   (with-current-buffer "*murk*"
368     (save-excursion
369       (goto-char murk-prompt-marker)
370       (let* ((inhibit-read-only t)
371              (old-pos (marker-position murk-prompt-marker))
372              (padded-timestamp (concat (format-time-string "%H:%M ")))
373              (padded-prefix (if prefix (concat prefix " ") ""))
374              (context-atom (if context (intern (murk-context->string context)) nil)))
375         (insert-before-markers
376          (murk--fill-strings
377           80
378           (+ (length padded-timestamp)
379              (length padded-prefix))
380           (propertize padded-timestamp
381                       'face 'murk-timestamp
382                       'read-only t
383                       'context context
384                       'invisible context-atom)
385           (propertize padded-prefix
386                       'read-only t
387                       'context context
388                       'invisible context-atom)
389           (murk-add-formatting
390            (propertize (concat (apply #'murk-buttonify-urls strings) "\n")
391                        'read-only t
392                        'context context
393                        'invisible context-atom)))))))
394   (murk-scroll-windows-to-last-line))
395
396 (defun murk-display-notice (context &rest notices)
397   (murk-display-string
398    context
399    (propertize murk-notice-prefix 'face 'murk-notice)
400    (apply #'concat notices)))
401
402 (defun murk-display-error (&rest messages)
403   (murk-display-string
404    nil
405    (propertize murk-error-prefix 'face 'murk-error)
406    (apply #'concat messages)))
407
408 (defun murk--start-of-final-line ()
409   (with-current-buffer "*murk*"
410     (save-excursion
411       (goto-char (point-max))
412       (line-beginning-position))))
413
414 (defun murk-scroll-windows-to-last-line ()
415   (with-current-buffer "*murk*"
416     (dolist (window (get-buffer-window-list))
417       (if (>= (window-point window) (murk--start-of-final-line))
418           (with-selected-window window
419             (recenter -1))))))
420
421
422
423 (defconst murk-url-regex
424   (rx (:
425        (group (+ alpha))
426        "://"
427        (group (or (+ (any alnum "." "-"))
428                   (+ (any alnum ":"))))
429        (opt (group (: ":" (+ digit))))
430        (opt (group (: "/"
431                       (opt
432                        (* (any alnum "-/.,#:%=&_?~@+"))
433                        (any alnum "-/#:%=&_~@+")))))))
434   "Imperfect regex used to find URLs in plain text.")
435
436 (defun murk-click-url (button)
437   (browse-url (button-get button 'url)))
438
439 (defun murk-buttonify-urls (&rest strings)
440   "Turn substrings which look like urls in STRING into clickable buttons."
441   (with-temp-buffer
442     (apply #'insert strings)
443     (goto-char (point-min))
444     (while (re-search-forward murk-url-regex nil t)
445       (let ((url (match-string 0)))
446         (make-text-button (match-beginning 0)
447                           (match-end 0)
448                           'action #'murk-click-url
449                           'url url
450                           'follow-link t
451                           'face 'button
452                           'help-echo "Open URL in browser.")))
453     (buffer-string)))
454
455 (defun murk-add-formatting (string)
456   (with-temp-buffer
457     (insert string)
458     (goto-char (point-min))
459     (let ((bold nil)
460           (italics nil)
461           (underline nil)
462           (strikethrough nil)
463           (prev-point (point)))
464       (while (re-search-forward (rx (or (any "\x02\x1D\x1F\x1E\x0F")
465                                         (: "\x03" (+ digit) (opt "," (* digit)))))
466                                 nil t)
467         (let ((beg (+ (match-beginning 0) 1)))
468           (if bold
469               (add-face-text-property prev-point beg '(:weight bold)))
470           (if italics
471               (add-face-text-property prev-point beg '(:slant italic)))
472           (if underline
473               (add-face-text-property prev-point beg '(:underline t)))
474           (if strikethrough
475               (add-face-text-property prev-point beg '(:strike-through t)))
476           (pcase (match-string 0)
477             ("\x02" (setq bold (not bold)))
478             ("\x1D" (setq italics (not italics)))
479             ("\x1F" (setq underline (not underline)))
480             ("\x1E" (setq strikethrough (not strikethrough)))
481             ("\x0F" ; Reset
482              (setq bold nil)
483              (setq italics nil)
484              (setq underline nil)
485              (setq strikethrough nil))
486             (_))
487           (delete-region (match-beginning 0) (match-end 0))
488           (setq prev-point (point)))))
489     (buffer-string)))
490
491
492 ;;; Message evaluation
493 ;;
494
495 (defun murk-eval-msg-string (server string)
496   (if murk-debug
497       (murk-display-string nil nil string))
498   (let* ((msg (murk-string->msg string)))
499     (pcase (murk-msg-cmd msg)
500       ("PING"
501        (murk-send-msg server
502         (murk-msg nil nil "PONG" (murk-msg-params msg))))
503
504       ("PONG")
505
506       (_
507        (murk-display-notice nil (murk-msg->string msg))))))
508
509 ;;; Commands
510 ;;
511
512 (defvar murk-command-table
513   '(("DEBUG" "Toggle debug mode on/off." murk-command-debug murk-boolean-completions)
514     ("HEADER" "Toggle display of header." murk-command-header murk-boolean-completions)
515     ("CONNECT" "Connect to an IRC network." murk-command-connect murk-network-completions)
516     ("NETWORKS" "List known IRC networks." murk-command-networks)
517     ("QUIT" "Disconnect from current network." murk-command-quit)
518     ("NICK" "Change nick." murk-command-nick)
519     ("MSG" "Send private message to user." murk-command-msg murk-nick-completions)
520     ("CLEAR" "Clear buffer text." murk-command-clear murk-context-completions)
521     ("HELP" "Display help on client commands." murk-command-help murk-help-completions))
522   "Table of commands explicitly supported by murk.")
523
524 (defun murk-command-help (params)
525   (if params
526       (let* ((cmd-str (upcase (car params)))
527              (row (assoc cmd-str murk-command-table #'equal)))
528         (if row
529             (progn
530               (murk-display-notice nil "Help for \x02" cmd-str "\x02:")
531               (murk-display-notice nil "  " (elt row 1)))
532           (murk-display-notice nil "No such (client-interpreted) command.")))
533     (murk-display-notice nil "Client-interpreted commands:")
534     (dolist (row murk-command-table)
535       (murk-display-notice nil "  \x02" (elt row 0) "\x02: " (elt row 1)))
536     (murk-display-notice nil "Use /HELP COMMAND to display information about a specific command.")))
537
538 (defun murk-command-debug (params)
539   (setq murk-debug 
540         (if params
541             (if (equal (upcase (car params)) "ON")
542                 t
543               nil)
544           (not murk-debug)))
545   (murk-display-notice nil "Debug mode now " (if murk-debug "on" "off") "."))
546
547 (defun murk-command-clear (params)
548   (if (not params)
549       (murk-clear-buffer)
550     (dolist (context params)
551       (murk-clear-context context))))
552
553
554 ;;; Command entering
555 ;;
556
557 (defun murk-enter-string (string)
558   (if (string-prefix-p "/" string)
559       (pcase string
560         ((rx (: "/" (let cmd-str (+ (not whitespace)))
561                 (opt (+ whitespace)
562                      (let params-str (+ anychar))
563                      string-end)))
564          (let ((command-row (assoc (upcase  cmd-str) murk-command-table #'equal))
565                (params (if params-str
566                            (split-string params-str nil t)
567                          nil)))
568            (if (and command-row (elt command-row 2))
569                (funcall (elt command-row 2) params)
570              (murk-send-msg (murk-msg nil nil (upcase cmd-str) params)))))
571         (_
572          (murk-display-error "Badly formed command.")))
573     (unless (string-empty-p string)
574       (if (murk-current-context)
575           (progn
576             (murk-send-msg server
577                            (murk-msg nil nil "PRIVMSG"
578                                      (murk-context-name murk-current-context)
579                                      string))
580             (murk-display-message murk-nick (murk-context->string (murk-current-context)) string))
581         (murk-display-error "No current context.")))))
582
583
584 ;;; Command history
585 ;;
586
587 (defvar murk-history nil
588   "Commands and messages sent in current session.")
589
590 (defvar murk-history-index nil)
591
592 (defun murk-history-cycle (delta)
593   (when murk-history
594     (with-current-buffer "*murk*"
595       (if murk-history-index
596           (setq murk-history-index
597                 (max 0
598                      (min (- (length murk-history) 1)
599                           (+ delta murk-history-index))))
600         (setq murk-history-index 0))
601       (delete-region murk-input-marker (point-max))
602       (insert (elt murk-history murk-history-index)))))
603
604
605 ;;; Interactive commands
606 ;;
607
608 (defun murk-enter ()
609   "Enter current contents of line after prompt."
610   (interactive)
611   (with-current-buffer "*murk*"
612     (let ((line (buffer-substring murk-input-marker (point-max))))
613       (push line murk-history)
614       (setq murk-history-index nil)
615       (let ((inhibit-read-only t))
616         (delete-region murk-input-marker (point-max)))
617       (murk-enter-string line))))
618
619
620 ;;; Mode
621 ;;
622
623 (defvar murk-mode-map
624   (let ((map (make-sparse-keymap)))
625     (define-key map (kbd "RET") 'murk-enter)
626     (define-key map (kbd "TAB") 'murk-complete-input)
627     (when (fboundp 'evil-define-key*)
628       (evil-define-key* 'motion map
629         (kbd "TAB") 'murk-complete-input))
630     map))
631
632 (define-derived-mode murk-mode text-mode "murk"
633   "Major mode for murk.")
634
635 (when (fboundp 'evil-set-initial-state)
636   (evil-set-initial-state 'murk-mode 'insert))
637
638 ;;; Main start procedure
639 ;;
640
641 (defun murk ()
642   "Start murk or just switch to the murk buffer if one already exists."
643   (interactive)
644   (if (get-buffer "*murk*")
645       (switch-to-buffer "*murk*")
646     (switch-to-buffer "*murk*")
647     (murk-mode)
648     (murk-setup-buffer))
649   "Started murk.")
650
651
652 ;;; murk.el ends here