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