Fixed some bugs, added POC context highlighting.
[lurk.git] / lurk.el
1 ;;; lurk.el --- Little Unified iRc Klient -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2021 Tim Vaughan
4
5 ;; Author: Tim Vaughan <timv@ughan.xyz>
6 ;; Created: 14 June 2021
7 ;; Version: 1.0
8 ;; Keywords: network
9 ;; Homepage: http://thelambdalab.xyz/lurk
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 'lurk)
32
33
34 ;;; Customizations
35 ;;
36
37 (defgroup lurk nil
38   "Little Unified iRc Klient."
39   :group 'network)
40
41 (defcustom lurk-nick "plugd"
42   "Default nick.")
43 (defcustom lurk-full-name "plugd"
44   "Default full name.")
45 (defcustom lurk-user-name "plugd"
46   "Default user name.")
47
48 (defcustom lurk-networks
49   '(("libera" "irc.libera.chat" 6697)
50     ("freenode" "chat.freenode.net" 6697)
51     ("local" "localhost" 6697))
52   "IRC networks.")
53
54 (defcustom lurk-allow-ipv6 nil
55   "Set to non-nil to allow use of IPv6.")
56
57 ;;; Faces
58 ;;
59
60 (defface lurk-text
61   '((t :inherit font-lock-preprocessor-face))
62   "Face used for Lurk text.")
63
64 (defface lurk-your-nick
65   '((t :inherit font-lock-constant-face))
66   "Face used for highlighting your nick.")
67
68 (defface lurk-prompt
69   '((t :inherit org-level-2))
70   "Face used for the prompt.")
71
72 (defface lurk-context
73   '((t :inherit org-list-dt))
74   "Face used for the context name in the prompt.")
75
76 (defface lurk-faded
77   '((t :inherit font-lock-preprocessor-face))
78   "Face used for faded Lurk text.")
79
80 (defface lurk-bold
81   '((t :inherit font-lock-function-name-face))
82   "Face used for bold Lurk text.")
83
84 (defface lurk-error
85   '((t :inherit font-lock-regexp-grouping-construct))
86   "Face used for Lurk error text.")
87
88 ;;; Global variables
89 ;;
90
91 (defvar lurk-version "Lurk v0.1")
92
93 (defvar lurk-notice-prefix
94   (concat
95    (propertize
96     "-" 'face 'lurk-faded)
97    (propertize
98     "!" 'face 'lurk-bold)
99    (propertize
100     "-" 'face 'lurk-faded)))
101
102 (defvar lurk-error-prefix
103   (propertize "!!!" 'face 'lurk-error))
104
105
106 (defvar lurk-prompt-string
107   (propertize "> " 'face 'lurk-prompt))
108
109
110 ;;; Network process
111 ;;
112
113 (defvar lurk-response "")
114
115 (defun lurk-filter (proc string)
116   (dolist (line (split-string (concat lurk-response string) "\n"))
117     (if (string-suffix-p "\r" line)
118         (lurk-eval-msg-string (string-trim line))
119       (setq lurk-response line))))
120
121 (defun lurk-sentinel (proc string)
122   (unless (equal "open" (string-trim string))
123     (lurk-display-error "Disconnected from server.")
124     (clrhash lurk-contexts)
125     (setq lurk-current-context nil)
126     (lurk-render-prompt)
127     (cancel-timer lurk-ping-timer)))
128
129 (defun lurk-start-process (network)
130   (let* ((row (assoc network lurk-networks))
131          (host (elt row 1))
132          (port (elt row 2))
133          (flags (seq-drop row 3)))
134     (make-network-process :name "lurk"
135                           :host host
136                           :service port
137                           :family (if lurk-allow-ipv6 nil 'ipv4)
138                           :filter #'lurk-filter
139                           :sentinel #'lurk-sentinel
140                           :nowait nil
141                           :tls-parameters (if (memq :notls flags)
142                                               nil
143                                             (cons 'gnutls-x509pki
144                                                   (gnutls-boot-parameters
145                                                    :type 'gnutls-x509pki
146                                                    :hostname host)))
147                           :buffer "*lurk*")))
148
149 (defvar lurk-ping-timer nil)
150 (defvar lurk-ping-period 60)
151
152 (defun lurk-ping-function ()
153   (lurk-send-msg (lurk-msg nil nil "PING" (car (process-contact (get-process "lurk")))))
154   (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))
155
156 (defun lurk-connect (network)
157   (if (get-process "lurk")
158       (lurk-display-error "Already connected.  Disconnect first.")
159     (if (not (assoc network lurk-networks))
160         (lurk-display-error "Network '" network "' is unknown.")
161       (clrhash lurk-contexts)
162       (setq lurk-current-context nil)
163       (lurk-start-process network)
164       (lurk-send-msg (lurk-msg nil nil "USER" lurk-user-name 0 "*" lurk-full-name))
165       (lurk-send-msg (lurk-msg nil nil "NICK" lurk-nick))
166       (setq lurk-ping-timer (run-with-timer lurk-ping-period nil #'lurk-ping-function)))))
167
168
169 (defun lurk-send-msg (msg)
170   (let ((proc (get-process "lurk")))
171     (if (and proc (eq (process-status proc) 'open))
172         (process-send-string proc (concat (lurk-msg->string msg) "\r\n"))
173       (lurk-display-error "No server connection established.")
174       (error "No server connection established"))))
175
176
177 ;;; Server messages
178 ;;
179
180 (defun lurk--as-string (obj)
181   (if obj
182       (with-output-to-string (princ obj))
183     nil))
184
185 (defun lurk-msg (tags src cmd &rest params)
186   (list (lurk--as-string tags)
187         (lurk--as-string src)
188         (upcase (lurk--as-string cmd))
189         (mapcar #'lurk--as-string
190                 (if (and params (listp (elt params 0)))
191                     (elt params 0)
192                   params))))
193
194 (defun lurk-msg-tags (msg) (elt msg 0))
195 (defun lurk-msg-src (msg) (elt msg 1))
196 (defun lurk-msg-cmd (msg) (elt msg 2))
197 (defun lurk-msg-params (msg) (elt msg 3))
198 (defun lurk-msg-trail (msg)
199   (let ((params (lurk-msg-params msg)))
200     (if params
201         (elt params (- (length params) 1)))))
202
203 (defvar lurk-msg-regex
204   (rx
205    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
206         (* whitespace))
207    (opt (: ":" (: (group (* (not (any space "!" "@"))))
208                   (* (not (any space)))))
209         (* whitespace))
210    (group (: (* (not whitespace))))
211    (* whitespace)
212    (opt (group (+ not-newline))))
213   "Regex used to parse IRC messages.
214 Note that this regex is incomplete.  Noteably, we discard the non-nick
215 portion of the source component of the message, as LURK doesn't use this.")
216
217 (defun lurk-string->msg (string)
218   (if (string-match lurk-msg-regex string)
219       (let* ((tags (match-string 1 string))
220              (src (match-string 2 string))
221              (cmd (upcase (match-string 3 string)))
222              (params-str (match-string 4 string))
223              (params
224               (if params-str
225                   (let* ((idx (cl-search ":" params-str))
226                          (l (split-string (string-trim (substring params-str 0 idx))))
227                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
228                     (append l r))
229                 nil)))
230         (apply #'lurk-msg (append (list tags src cmd) params)))
231     (error "Failed to parse string " string)))
232
233 (defun lurk--filtered-join (&rest args)
234   (string-join (seq-filter (lambda (el) el) args) " "))
235
236 (defun lurk-msg->string (msg)
237   (let ((tags (lurk-msg-tags msg))
238         (src (lurk-msg-src msg))
239         (cmd (lurk-msg-cmd msg))
240         (params (lurk-msg-params msg)))
241     (lurk--filtered-join
242      (if tags (concat "@" tags) nil)
243      (if src (concat ":" src) nil)
244      cmd
245      (if (> (length params) 1)
246          (string-join (seq-take params (- (length params) 1)) " ")
247        nil)
248      (if (> (length params) 0)
249          (concat ":" (elt params (- (length params) 1)))
250        nil))))
251
252
253 ;;; Contexts
254 ;;
255
256 (defvar lurk-current-context nil)
257 (defvar lurk-contexts (make-hash-table :test #'equal))
258
259 (defun lurk-add-context (name)
260   (puthash name nil lurk-contexts))
261
262 (defun lurk-del-context (name)
263   (remhash name lurk-contexts))
264
265 (defun lurk-get-context-users (name)
266   (gethash name lurk-contexts))
267
268 (defun lurk-add-context-users (context users)
269   (puthash context
270            (append users
271                    (gethash context lurk-contexts))
272            lurk-contexts))
273
274 (defun lurk-del-context-user (context user)
275   (puthash context
276            (remove user (gethash context lurk-contexts))
277            lurk-contexts))
278
279 (defun lurk-del-user (user)
280   (dolist (context (lurk-get-context-list))
281     (lurk-del-context-user context user)))
282
283 (defun lurk-get-context-type (name)
284   (cond
285    ((string-prefix-p "#" name) 'channel)
286    ((string-match-p (rx (or "." "localhost")) name) 'host)
287    (t 'nick)))
288
289 (defun lurk-get-context-list ()
290   (let ((res nil))
291     (maphash (lambda (key val)
292                (cl-pushnew key res))
293              lurk-contexts)
294     res))
295
296 (defun lurk-get-next-context (&optional prev)
297   (if lurk-current-context
298       (let* ((context-list (if prev
299                                (reverse (lurk-get-context-list))
300                              (lurk-get-context-list)))
301              (context-list* (member lurk-current-context context-list)))
302         (if (> (length context-list*) 1)
303             (cadr context-list*)
304           (car context-list)))
305     nil))
306
307 (defun lurk-cycle-contexts (&optional rev)
308   (if lurk-current-context
309       (progn
310         (setq lurk-current-context (lurk-get-next-context rev))
311         (lurk-render-prompt))
312     (lurk-display-error "No channels joined.")))
313
314 (defun lurk-cycle-contexts-forward ()
315   (interactive)
316   (lurk-cycle-contexts))
317
318 (defun lurk-cycle-contexts-reverse ()
319   (interactive)
320   (lurk-cycle-contexts t))
321
322
323 ;;; Buffer
324 ;;
325
326 (defun lurk-display-string (&rest strings)
327   (with-current-buffer (get-buffer-create "*lurk*")
328     (save-excursion
329       (goto-char lurk-prompt-marker)
330       (let ((inhibit-read-only t)
331             (old-pos (marker-position lurk-prompt-marker))
332             (adaptive-fill-regexp (rx (= 6 anychar))))
333         (insert-before-markers
334          (propertize (concat (format-time-string "%H:%M") " ")
335                      'face 'lurk-text
336                      'read-only t)
337          (propertize (concat (apply #'concat strings) "\n")
338                      'read-only t))
339         (fill-region old-pos lurk-prompt-marker)))))
340
341 (defun lurk-render-prompt ()
342   (with-current-buffer "*lurk*"
343     (let ((update-point (= lurk-input-marker (point)))
344           (update-window-points (mapcar (lambda (w)
345                                           (list (= (window-point w) lurk-input-marker)
346                                                 w))
347                                         (get-buffer-window-list nil nil t))))
348       (save-excursion
349         (set-marker-insertion-type lurk-prompt-marker nil)
350         (set-marker-insertion-type lurk-input-marker t)
351         (let ((inhibit-read-only t))
352           (delete-region lurk-prompt-marker lurk-input-marker)
353           (goto-char lurk-prompt-marker)
354           (insert
355            (propertize (if lurk-current-context
356                            lurk-current-context
357                          "")
358                        'face 'lurk-context
359                        'read-only t)
360            (propertize lurk-prompt-string
361                        'face 'lurk-prompt
362                        'read-only t
363                        'rear-nonsticky t)))
364         (set-marker-insertion-type lurk-input-marker nil))
365       (if update-point
366           (goto-char lurk-input-marker))
367       (dolist (v update-window-points)
368         (if (car v)
369             (set-window-point (cadr v) lurk-input-marker))))))
370   
371 (defvar lurk-prompt-marker nil
372   "Marker for prompt position in LURK buffer.")
373
374 (defvar lurk-input-marker nil
375   "Marker for prompt position in LURK buffer.")
376
377 (defun lurk-setup-buffer ()
378   (with-current-buffer (get-buffer-create "*lurk*")
379     (setq-local scroll-conservatively 1)
380     (if (markerp lurk-prompt-marker)
381         (set-marker lurk-prompt-marker (point-max))
382       (setq lurk-prompt-marker (point-max-marker)))
383     (if (markerp lurk-input-marker)
384         (set-marker lurk-input-marker (point-max))
385       (setq lurk-input-marker (point-max-marker)))
386     (goto-char (point-max))
387     (lurk-render-prompt)))
388
389
390 ;;; Output formatting
391 ;;
392
393 (defun lurk-display-message (from to text)
394   (let ((context (if (eq 'channel (lurk-get-context-type to))
395                      to
396                    (if (equal to lurk-nick) from to))))
397     (lurk-display-string
398      (propertize
399       (pcase (lurk-get-context-type to)
400         ('channel (concat to " <" from "> " text))
401         ('nick (concat "[" from " -> " to "] " text))
402         (_
403          (error "Unsupported context type")))
404       'face 'lurk-text
405       'help-echo (concat "Context: " context)
406       'context context))))
407
408 (defun lurk-display-notice (context &rest notices)
409   (lurk-display-string
410    (propertize
411     (concat lurk-notice-prefix " " (apply #'concat notices))
412     'help-echo (concat "Context: " (or context "none"))
413     'context context)))
414
415 (defun lurk-display-error (&rest messages)
416   (lurk-display-string
417    (concat lurk-error-prefix " "
418            (propertize (apply #'concat messages)
419                        'face 'lurk-error))))
420
421 (defun lurk-highlight-context (context)
422   (with-current-buffer "*lurk*"
423     (let* ((pos lurk-prompt-marker)
424            (nextpos (previous-single-property-change pos 'context))
425            (inhibit-read-only t))
426       (while (> pos nextpos)
427         (let ((thiscontext (get-text-property nextpos 'context)))
428           (if thiscontext
429               (if (equal context thiscontext)
430                   (add-text-properties nextpos pos
431                                        '(face (foreground-color . "green")))
432                 (add-text-properties nextpos pos
433                                      '(face (foreground-color . "blue"))))
434             (add-text-properties nextpos pos
435                                  '(face lurk-text)))
436           thiscontext
437           (setq pos nextpos)
438           (setq nextpos (previous-single-property-change pos 'context nil 1)))))))
439
440 ;;; Message evaluation
441 ;;
442
443 (defun lurk-eval-msg-string (string)
444   ;; (lurk-display-string string)
445   (let* ((msg (lurk-string->msg string)))
446     (pcase (lurk-msg-cmd msg)
447       ("PING"
448        (lurk-send-msg
449         (lurk-msg nil nil "PONG" (lurk-msg-params msg))))
450        ;; (lurk-display-notice nil "ping-pong (server initiated)"))
451
452       ("PONG")
453        ;; (lurk-display-notice nil "ping-pong (client initiated)"))
454
455       ("353" ; NAMEREPLY
456        (let* ((params (lurk-msg-params msg))
457               (channel (elt params 2))
458               (names (split-string (elt params 3))))
459          (lurk-add-context-users channel names)))
460
461       ("366" ; ENDOFNAMES
462        (let* ((params (lurk-msg-params msg))
463               (channel (elt params 1)))
464          (lurk-display-notice
465           channel
466           (lurk--as-string (length (lurk-get-context-users channel)))
467           " users in " channel)))
468
469       ((rx (= 3 (any digit)))
470        (lurk-display-notice nil (mapconcat 'identity (cdr (lurk-msg-params msg)) " ")))
471
472       ((and "JOIN"
473             (guard (equal lurk-nick (lurk-msg-src msg))))
474        (let ((channel (car (lurk-msg-params msg))))
475          (lurk-add-context channel)
476          (setq lurk-current-context channel)
477          (lurk-display-notice channel "Joining channel " channel)
478          (lurk-render-prompt)))
479
480       ("JOIN"
481        (let ((channel (car (lurk-msg-params msg)))
482              (nick (lurk-msg-src msg)))
483          (lurk-add-context-users channel (list nick))
484          (lurk-display-notice channel nick " joined channel " channel)))
485
486       ((and "PART"
487             (guard (equal lurk-nick (lurk-msg-src msg))))
488        (let ((channel (car (lurk-msg-params msg))))
489          (lurk-display-notice channel "Left channel " channel)
490          (lurk-del-context channel)
491          (if (equal channel lurk-current-context)
492              (setq lurk-current-context (lurk-get-next-context)))
493          (lurk-render-prompt)))
494
495       ("PART"
496        (let ((channel (car (lurk-msg-params msg)))
497              (nick (lurk-msg-src msg)))
498          (lurk-del-context-user channel nick)
499          (lurk-display-notice channel nick " left channel " channel)))
500
501       ("QUIT"
502        (let ((nick (lurk-msg-src msg))
503              (reason (mapconcat 'identity (lurk-msg-params msg) " ")))
504          (lurk-del-user nick)
505          (lurk-display-notice nil nick " quit: " reason)))
506
507       ((and "NICK"
508             (guard (equal lurk-nick (lurk-msg-src msg))))
509        (setq lurk-nick (car (lurk-msg-params msg)))
510        (lurk-display-notice nil "Set nick to " lurk-nick))
511
512       ("NICK"
513        (let ((old-nick (lurk-msg-src msg))
514              (new-nick (car (lurk-msg-params msg))))
515          (lurk-display-notice nil nick " is now known as " new-nick)
516          (lurk-rename-user nick new-nick)))
517
518       ("NOTICE"
519        (let ((nick (lurk-msg-src msg))
520              (channel (car (lurk-msg-params msg)))
521              (text (cadr (lurk-msg-params msg))))
522          (pcase text
523            ((rx (: "\01VERSION "
524                    (let version (* (not "\01")))
525                    "\01"))
526             (lurk-display-notice nil "CTCP version reply from " nick ": " version))
527            (_
528             (lurk-display-notice nil text)))))
529
530       ("PRIVMSG"
531        (let* ((from (lurk-msg-src msg))
532               (params (lurk-msg-params msg))
533               (to (car params))
534               (text (cadr params)))
535          (pcase text
536            ("\01VERSION\01"
537             (let ((version-string (concat lurk-version " - running on GNU Emacs " emacs-version)))
538               (lurk-send-msg (lurk-msg nil nil "NOTICE"
539                                        (list from (concat "\01VERSION "
540                                                           version-string
541                                                           "\01")))))
542             (lurk-display-notice nil "CTCP version request received from " from))
543
544            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
545             (lurk-send-msg (lurk-msg nil nil "NOTICE" (list from ping)))
546             (lurk-display-notice "CTCP ping received from " from))
547
548            ("\01USERINFO\01"
549             (lurk-display-notice "CTCP userinfo request from " from " (no response sent)"))
550
551            (_
552             (lurk-display-message from to text)))))
553       (_
554        (lurk-display-string (lurk-msg->string msg))))))
555
556
557 ;;; Command entering
558 ;;
559
560 (defun lurk-enter-string (string)
561   (if (string-prefix-p "/" string)
562       (pcase (substring string 1)
563         ((rx (: "CONNECT " (let network (* not-newline))))
564          (lurk-display-notice nil "Attempting to connect to " network "...")
565          (lurk-connect network))
566
567         ((rx (: "TOPIC " (let new-topic (* not-newline))))
568          (lurk-send-msg (lurk-msg nil nil "TOPIC" lurk-current-context new-topic)))
569
570         ((rx (: "ME " (let action (* not-newline))))
571          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
572                                   (list lurk-current-context
573                                         (concat "\01ACTION " action "\01"))))
574          (lurk-display-action lurk-nick action))
575
576         ((rx (: "VERSION" " " (let nick (* (not whitespace)))))
577          (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
578                                   (list nick "\01VERSION\01")))
579          (lurk-display-notice nil "CTCP version request sent to " nick))
580
581         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
582          (if (or lurk-current-context channel)
583              (lurk-send-msg (lurk-msg nil nil "PART" (if channel
584                                                          channel
585                                                        lurk-current-context)))
586            (lurk-display-error "No current channel to leave.")))
587
588         ((rx "MSG "
589              (let to (* (not whitespace)))
590              " "
591              (let text (* not-newline)))
592          (lurk-send-msg (lurk-msg nil nil "PRIVMSG" to text))
593          (lurk-display-message lurk-nick to text))
594
595         ((rx (: (let cmd-str (+ (not whitespace)))
596                 (opt (: " " (let params-str (* not-newline))))))
597          (lurk-send-msg (lurk-msg nil nil (upcase cmd-str)
598                                   (if params-str
599                                       (split-string params-str)
600                                     nil)))))
601
602     (unless (string-empty-p string)
603       (if lurk-current-context
604           (progn
605             (lurk-send-msg (lurk-msg nil nil "PRIVMSG"
606                                      lurk-current-context
607                                      string))
608             (lurk-display-message lurk-nick lurk-current-context string))
609         (lurk-display-error "No current context.")))))
610
611 (defun lurk-enter ()
612   "Enter current contents of line after prompt."
613   (interactive)
614   (with-current-buffer "*lurk*"
615     (lurk-enter-string
616      (buffer-substring lurk-input-marker (point-max)))
617     (let ((inhibit-read-only t))
618       (delete-region lurk-input-marker (point-max)))))
619
620
621 ;;; Mode
622 ;;
623
624 (defvar lurk-mode-map
625   (let ((map (make-sparse-keymap)))
626     (define-key map (kbd "RET") 'lurk-enter)
627     (define-key map (kbd "<C-tab>") 'lurk-cycle-contexts-forward)
628     (define-key map (kbd "<C-S-tab>") 'lurk-cycle-contexts-reverse)
629     map))
630
631 (define-derived-mode lurk-mode text-mode "lurk"
632   "Major mode for LURK.")
633
634 (when (fboundp 'evil-set-initial-state)
635   (evil-set-initial-state 'lurk-mode 'insert))
636
637 ;;; Main start procedure
638 ;;
639
640 (defun lurk ()
641   "Switch to *lurk* buffer."
642   (interactive)
643   (if (get-buffer "*lurk*")
644       (switch-to-buffer "*lurk*")
645     (switch-to-buffer "*lurk*"))
646   (lurk-mode)
647   (lurk-setup-buffer)
648   "Started LURK.")
649
650
651
652 ;;; lurk.el ends here