Repository navigation
Expand file tree
/
Copy pathcoil.el
More file actions
8000
1833 lines (1644 loc) · 83.3 KB
/
Copy pathcoil.el
File metadata and controls
1833 lines (1644 loc) · 83.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; coil.el --- A Jupyter session in an Emacs buffer -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Daniel Gomez
;; Author: Daniel Gomez
;; Version: 0.1
;; Package-Requires: ((emacs "30.1"))
;; Keywords: languages, processes
;; URL: https://github.com/dangom/coil
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; A session with a Jupyter kernel, one per project, in an ordinary buffer of
;; cells: the code, then what it printed, its value, its figures, its error.
;; The kernel outlives Emacs; the session buffer comes back from a log.
;;
;; This file knows nothing of any language: a backend (coil-python.el) says
;; how to start the kernel, and sends code to it with `coil-execute'. The
;; kernel is spoken to through bridge/coil_bridge.py, a plain subprocess, in
;; JSON lines.
;;
;; Output is untrusted: it is inserted as text, with its colours, and figures
;; (PNG and JPEG) as images. Nothing in it is acted on. See the README.
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'ansi-color)
(require 'text-property-search)
(require 'ring)
(declare-function project-root "project" (project))
(defgroup coil nil
"A Jupyter session in an Emacs buffer."
:group 'processes
:prefix "coil-")
(defcustom coil-state-directory
(expand-file-name "coil/" (or (getenv "XDG_STATE_HOME") "~/.local/state"))
"Where coil keeps each project's kernel connection, log and figures.
Only you can read it: it is made mode 0700, its files 0600."
:type 'directory)
(defcustom coil-kernel-idle-hours 48
"Hours a kernel may run nothing before it is shut down; nil, never.
A kernel outlives Emacs, so this is kept by a watch beside the kernel, not
by Emacs: it holds whether Emacs is open or not, with the value this had
when the watch began, as the kernel started. A run that lasts longer is
not cut short; only a kernel that waits does. Its variables are lost; its
log is kept, and the session says why the kernel went."
:type '(choice number (const :tag "Never" nil)))
(defcustom coil-log-cells 300
"How many cells of the log are shown again when a session buffer is made."
:type 'natnum)
(defcustom coil-log-keep 5
"How many past sessions' logs are kept per project, the current one aside.
A log holds what was run and what it printed: nil keeps none at all."
:type '(choice natnum (const :tag "Keep no log" nil)))
(defcustom coil-fold-lines 200
"Output of a cell longer than this many lines is folded, TAB to unfold."
:type 'natnum)
(defcustom coil-fold-input-lines 12
"Code of a cell longer than this many lines is folded, TAB to unfold.
Its first `coil-fold-input-shown' lines stay in view."
:type 'natnum)
(defcustom coil-fold-input-shown 6
"How many lines of folded code stay in view."
:type 'natnum)
(defcustom coil-image-max-width 900
"The widest a figure is shown, in pixels, or nil for the window's width."
:type '(choice natnum (const nil)))
(defcustom coil-max-image-pixels (* 40 1000 1000)
"A PNG of more pixels than this is not drawn."
:type 'natnum)
(defcustom coil-cell-done-functions nil
"Functions called with the session and the cell, once a cell is done."
:type 'hook)
(defcustom coil-figure-functions nil
"Functions called with the session, the cell and the image file of a figure.
Run for each figure a cell shows, as it comes."
:type 'hook)
(defvar coil-input-request-functions nil
"Functions called with the session, the cell and an input_request event.
The first to return non-nil has taken the question (as the debugger's, see
coil-debug.el); if none does, it is asked in the minibuffer.")
(defvar coil-breakpoints-function nil
"A function of the session and the cell about to run, returning where it is
to stop: a list of [FILE LINE TEMPORARY], FILE the name of the kernel's file
or `:null' for the cell's own, TEMPORARY t or `:false'; or nil, to just run.")
(defvar coil-bridge
(expand-file-name "bridge/coil_bridge.py"
(file-name-directory (or load-file-name buffer-file-name)))
"The bridge, run by the environment's own interpreter.")
(defvar coil-backends nil
"How to start a kernel, by major mode: (MODE . PLIST).
PLIST has :name, a string; :interpreter, a function returning the Python
that runs the bridge -- it must have jupyter_client; :environment, optional,
a function of the project root returning the kernel's `process-environment'
when it is not the buffer's (nil to keep the buffer's); :kernel, the kernel's
argv, with {python} and {connection_file} filled in by the bridge; :mode,
the major mode its code is shown in; :missing, a function called with the
session when the bridge finds jupyter_client missing.")
(defface coil-header '((t :inherit shadow))
"The line above each cell.")
(defface coil-prompt '((t :inherit minibuffer-prompt))
"The prompt of the session buffer.")
(defface coil-ok '((t :inherit success))
"A cell that ran.")
(defface coil-failed '((t :inherit error))
"A cell that failed.")
(defface coil-stderr '((t :inherit warning))
"What a cell wrote to stderr.")
(defface coil-code '((((background light)) :extend t :background "gray96")
(t :extend t :background "gray15"))
"The code of a cell: a faint tint, to tell it from its output.")
(defface coil-rule '((((background light)) :underline (:color "gray85" :position t))
(t :underline (:color "gray25" :position t)))
"The hairline under each cell, across the window.")
;;; State, trust
(defun coil--state-dir (root &optional make)
"The directory of ROOT's kernel and log, made (mode 0700) if MAKE."
(let ((dir (expand-file-name (substring (secure-hash 'sha256 root) 0 12)
coil-state-directory)))
(when make
(with-file-modes #o700
(make-directory dir t))
(set-file-modes coil-state-directory #o700)
(set-file-modes dir #o700)
(let ((name (expand-file-name "root" dir)))
(unless (file-exists-p name)
(with-file-modes #o600
(write-region root nil name nil 'silent)))))
dir))
(defun coil--trust-file ()
(expand-file-name "trusted.eld" coil-state-directory))
(defun coil--trusted ()
(let ((file (coil--trust-file)))
(when (file-readable-p file)
(with-temp-buffer
(insert-file-contents file)
(ignore-errors (read (current-buffer)))))))
(defun coil-trusted-p (root)
"Whether ROOT may have a kernel started in it."
(member (file-name-as-directory root) (coil--trusted)))
(defun coil--write-trusted (roots)
(with-file-modes #o700 (make-directory coil-state-directory t))
(with-file-modes #o600
(with-temp-file (coil--trust-file)
(prin1 roots (current-buffer)))))
(defun coil-trust (root)
"Trust ROOT: let coil start a kernel there, which runs the project's code."
(interactive (list (coil--root)))
(setq root (file-name-as-directory (file-truename root)))
(unless (coil-trusted-p root)
(coil--write-trusted (cons root (coil--trusted))))
root)
(defun coil-untrust (root)
"Stop trusting ROOT. Its running kernel, if any, is left to be shut down."
(interactive (list (completing-read "Untrust: " (coil--trusted) nil t)))
(coil--write-trusted (delete (file-name-as-directory root) (coil--trusted))))
(defun coil--ensure-trusted (root)
(unless (coil-trusted-p root)
(if (y-or-n-p (format "Start a kernel in %s? It runs the project's code (its environment's activation, startup files): trust it? "
(abbreviate-file-name root)))
(coil-trust root)
(user-error "Not trusted: %s" (abbreviate-file-name root)))))
;;; Sessions
(cl-defstruct (coil-session (:constructor coil--session-create) (:copier nil))
root name state backend process buffer env path
(next-id 0) (requests (make-hash-table)) queue (partial "")
ready status pid fresh
completing ; a completion request not answered yet
asking ; (CELL . PROMPT): the kernel's question,
; answered at the session's prompt
(codefiles (make-hash-table :test #'equal))) ; the kernel's file of a cell -> it
(cl-defstruct (coil-cell (:constructor coil--cell-create) (:copier nil))
uid code file line count status start duration outputs
beg ostart out clear-pending overlay
origin ; the line of FILE that is the code's first
codefile) ; the file the kernel runs it as
(defvar coil--sessions (make-hash-table :test #'equal)
"The sessions of this Emacs, by project root.")
(defvar-local coil--session nil
"The session of this session buffer.")
(defvar-local coil--prompt-start nil "Where the prompt begins.")
(defvar-local coil--input-start nil "Where the input begins.")
(defvar-local coil--ready-at nil "Where to say the kernel is ready: above what waits for it.")
(defvar coil-root-function #'coil--default-root
"A function returning the project root of the current buffer.")
(defun coil--default-root ()
(or (and (fboundp 'doom-project-root) (doom-project-root))
(and (fboundp 'project-current)
(when-let* ((project (project-current))) (project-root project)))
default-directory))
(defun coil--root ()
(if coil--session
(coil-session-root coil--session)
(file-name-as-directory (file-truename (funcall coil-root-function)))))
(defun coil--backend ()
(or (and coil--session (coil-session-backend coil--session))
(cdr (cl-find-if (lambda (entry) (derived-mode-p (car entry))) coil-backends))
(user-error "coil does not know how to run %s" major-mode)))
(defun coil--live-p (session)
(and session (process-live-p (coil-session-process session))))
(defun coil-current-session (&optional start)
"This buffer's session; started first, if START and there is none."
(let* ((root (coil--root))
(session (or coil--session (gethash root coil--sessions))))
(cond ((coil--live-p session) session)
(start (coil--start root (if session (coil-session-backend session)
(coil--backend))
session)))))
(defun coil--start (root backend &optional session)
"Start the bridge for ROOT, attaching to its kernel or starting one."
(coil--ensure-trusted root)
(let* ((session (or session
(coil--session-create
:root root :backend backend
:name (file-name-nondirectory (directory-file-name root))
;; The environment of the buffer it is started from,
;; which envrc made the project's: kept for restarts.
:env process-environment :path exec-path)))
(state (coil--state-dir root t))
;; The backend may name the kernel's environment itself (a pixi
;; project's dev one); else it is the buffer's, kept from the start.
(_ (when-let* ((environment (plist-get backend :environment))
(env (funcall environment root)))
(setf (coil-session-env session) env
(coil-session-path session)
(append (parse-colon-path (getenv-internal "PATH" env))
(list exec-directory)))))
(python (let ((process-environment (coil-session-env session))
(exec-path (coil-session-path session)))
(funcall (plist-get backend :interpreter))))
(process-environment (coil-session-env session))
(exec-path (coil-session-path session))
(default-directory root))
;; One bridge per session: an old one is let go (its kernel stays).
(when (process-live-p (coil-session-process session))
(delete-process (coil-session-process session)))
(unless python
(user-error "No interpreter for the kernel in %s" (abbreviate-file-name root)))
;; What attaching from elsewhere (the list of sessions) needs to know.
(with-file-modes #o600
(write-region (prin1-to-string (list :interpreter python
:backend (plist-get backend :name)))
nil (expand-file-name "bridge.eld" state) nil 'silent))
(setf (coil-session-state session) state
(coil-session-ready session) nil
(coil-session-status session) (if (equal (coil-session-status session)
"missing jupyter_client")
"missing jupyter_client"
"starting")
(coil-session-partial session) ""
(coil-session-completing session) nil)
;; What was sent while the kernel's tools were being installed still
;; waits; otherwise what was asked of the bridge before is gone with it.
(unless (equal (coil-session-status session) "missing jupyter_client")
(setf (coil-session-queue session) nil)
(clrhash (coil-session-requests session)))
(puthash root session coil--sessions)
(setf (coil-session-process session)
(make-process
:name (format "coil %s" (coil-session-name session))
:command (list python "-I" coil-bridge
"--state" state "--cwd" root
"--kernel" (json-serialize (vconcat (plist-get backend :kernel)))
"--idle" (number-to-string
(if coil-kernel-idle-hours
(round (* 3600 coil-kernel-idle-hours))
0)))
:connection-type 'pipe
:coding 'utf-8-unix
:noquery t
:stderr (get-buffer-create (format " *coil stderr %s*" (coil-session-name session)))
:filter (lambda (process output) (coil--filter session process output))
:sentinel (lambda (process event) (coil--sentinel session process event))))
(with-current-buffer (coil--buffer session)
;; Above what is sent from now on -- or above what already waits.
(unless (and coil--ready-at (marker-position coil--ready-at)
(coil-session-queue session))
(setq coil--ready-at (copy-marker coil--prompt-start))))
(coil--refresh-mode-line session)
session))
(defun coil--send (session op &rest fields)
"Send OP with FIELDS (a plist) to SESSION's bridge; return the request id.
Before the kernel is ready, it waits in a queue."
(let* ((id (cl-incf (coil-session-next-id session)))
(line (concat (json-serialize (append (list :id id :op op) fields)) "\n")))
(if (coil-session-ready session)
(process-send-string (coil-session-process session) line)
(setf (coil-session-queue session)
(append (coil-session-queue session) (list line))))
id))
(defun coil--request (session op timeout &rest fields)
"Send OP and wait for its reply, up to TIMEOUT seconds; nil if none came."
(when (coil-session-ready session)
(let* ((reply 'waiting)
(id (apply #'coil--send session op fields))
(until (+ (float-time) timeout)))
(puthash id (lambda (content) (setq reply content)) (coil-session-requests session))
(while (and (eq reply 'waiting) (< (float-time) until)
(process-live-p (coil-session-process session)))
(accept-process-output (coil-session-process session) 0.02))
(remhash id (coil-session-requests session))
(unless (eq reply 'waiting) reply))))
(defun coil--filter (session process output)
;; Only the session's own bridge is heard: one let go, or of a session
;; since replaced, could otherwise write into a buffer no longer its own.
(when (and (eq process (coil-session-process session))
(eq session (gethash (coil-session-root session) coil--sessions)))
(coil--filter-1 session output)))
(defun coil--filter-1 (session output)
(let ((text (concat (coil-session-partial session) output))
(start 0))
(while (string-match "\n" text start)
(let ((line (substring text start (match-beginning 0))))
(setq start (match-end 0))
(unless (string-empty-p line)
(condition-case err
(coil--event session (json-parse-string line :object-type 'alist
:array-type 'list
:null-object nil
:false-object nil))
(error (message "coil: %s" (error-message-string err)))))))
(setf (coil-session-partial session) (substring text start))))
(defun coil--sentinel (session process _event)
(unless (process-live-p process)
(setf (coil-session-ready session) nil)
(unless (member (coil-session-status session) '("shut down" "restarting"))
(setf (coil-session-status session) "detached"))
(coil--refresh-mode-line session)))
(defun coil--event (session event)
(let ((kind (alist-get 'event event))
(cell (gethash (alist-get 'id event) (coil-session-requests session))))
(pcase kind
("ready" (coil--ready session event))
("missing"
(setf (coil-session-status session) "missing jupyter_client")
(if-let* ((missing (plist-get (coil-session-backend session) :missing)))
(run-at-time 0 nil missing session)
(message "coil: the environment has no jupyter_client")))
("fatal"
(setf (coil-session-status session) "failed")
(message "coil: %s" (alist-get 'message event)))
("died"
(unless (member (coil-session-status session) '("restarting" "shut down"))
(let ((ended (alist-get 'ended event)))
(setf (coil-session-status session) (if ended "shut down" "kernel died"))
(coil--note session (concat (if ended (coil--ended-text "The kernel" ended)
"The kernel died.")
" C-c C-z or any send starts a new one.")))))
("shutdown" (setf (coil-session-status session) "shut down"))
("reply"
(remhash (alist-get 'id event) (coil-session-requests session))
(when (functionp cell) (funcall cell (alist-get 'content event))))
("input_request" (run-at-time 0 nil #'coil--input-request session cell event))
(_ (when (coil-cell-p cell) (coil--cell-event session cell kind event))))
(coil--refresh-mode-line session)))
(defun coil--ready (session event)
(setf (coil-session-ready session) t
(coil-session-status session) "idle"
(coil-session-pid session) (alist-get 'pid event)
(coil-session-fresh session) (alist-get 'fresh event))
(coil--stop-asking session)
(with-current-buffer (coil--buffer session)
(when (alist-get 'fresh event)
(clrhash (coil-session-codefiles session))
(coil--rotate-log session))
(coil--note session (concat (when-let* ((ended (alist-get 'ended event)))
(concat (coil--ended-text "The last kernel" ended) "\n"))
(coil--kernel-line event))
coil--ready-at))
(dolist (line (coil-session-queue session))
(process-send-string (coil-session-process session) line))
(setf (coil-session-queue session) nil))
(defun coil--ended-text (kernel ended)
"That KERNEL was shut down idle, from ENDED, the bridge's account of it."
(format "%s ran nothing for %s h, and was shut down %s (`coil-kernel-idle-hours')."
kernel
(string-trim-right (format "%.1f" (/ (alist-get 'idle ended) 3600.0)) "\\.0")
(format-time-string "%a %e %b, %H:%M" (alist-get 'at ended))))
(defun coil--kernel-line (event)
"What the kernel of the ready EVENT is: language, shell, environment, pid."
(let ((language (alist-get 'language event))
(implementation (alist-get 'implementation event)))
(string-join
(delq nil
(list (if (alist-get 'fresh event) "New kernel" "Attached to the running kernel")
(and language (concat (capitalize language) " " (or (alist-get 'version event) "")))
(and implementation (not (equal implementation language))
(concat (if (equal implementation "ipython") "IPython" implementation)
" " (or (alist-get 'implementation_version event) "")))
(and (alist-get 'environment event)
(abbreviate-file-name (alist-get 'environment event)))
(format "pid %s" (alist-get 'pid event))))
" · ")))
;;; The session buffer
(defvar-local coil--history nil "What was typed, a ring.")
(defvar-local coil--history-index nil)
(defvar-keymap coil-mode-map
"RET" #'coil-return
"C-j" #'newline-and-indent
"C-<return>" #'coil-submit
"TAB" #'completion-at-point
"M-p" #'coil-previous-input
"M-n" #'coil-next-input
"C-c C-c" #'coil-interrupt
"C-c C-n" #'coil-next-cell
"C-c C-p" #'coil-previous-cell
"C-c C-k" #'coil-interrupt
"C-c C-q" #'coil-shutdown
"C-c C-d" #'coil-detach
"C-c C-o" #'coil-plots
"C-a" #'coil-beginning-of-line)
(defvar-keymap coil-cell-map
:doc "Keys on a cell: the output is read-only, so letters are free."
"n" #'coil-next-cell
"p" #'coil-previous-cell
"RET" #'coil-visit-source
"w" #'coil-copy-output
"o" #'coil-open-figure
"c" #'coil-pin-figure
"P" #'coil-plots
"TAB" #'coil-toggle-fold)
(define-derived-mode coil-mode nil "coil"
"A session with a Jupyter kernel.
Type at the prompt; RET runs what is there when it is complete, and
starts an indented line when it is not. Above, the cells:
\\{coil-cell-map}
\\{coil-mode-map}"
(setq-local coil--history (make-ring 500)
coil--prompt-start (point-min-marker)
coil--input-start (point-min-marker)
truncate-lines nil
word-wrap t
mode-line-process '(:eval (coil--mode-line-process)))
(set-marker-insertion-type coil--prompt-start t)
(add-hook 'completion-at-point-functions #'coil-completion-at-point nil t)
(add-hook 'eldoc-documentation-functions #'coil-eldoc nil t)
(eldoc-mode 1)
(font-lock-mode -1))
(defun coil--buffer (session)
"SESSION's buffer, made if need be, with its history from the log."
(let ((buffer (coil-session-buffer session)))
(if (buffer-live-p buffer)
buffer
(setq buffer (get-buffer-create (format "*coil: %s*" (coil-session-name session))))
;; Never another live session's buffer, which has the same name.
(when-let* ((other (buffer-local-value 'coil--session buffer))
((not (eq other session)))
((coil--live-p other)))
(setq buffer (generate-new-buffer (buffer-name buffer))))
;; Known as the session's before it is filled: filling it asks for it.
(setf (coil-session-buffer session) buffer)
(with-current-buffer buffer
(coil-mode)
(setq coil--session session
default-directory (coil-session-root session))
(setq-local process-environment (coil-session-env session)
exec-path (coil-session-path session))
(let ((inhibit-read-only t))
(erase-buffer)
(set-marker coil--prompt-start (point-min))
(coil--insert-prompt)
(coil--replay-log session)))
buffer)))
(defun coil--insert-prompt (&optional text)
"Make the prompt TEXT, or the usual one; what is typed after it stays."
(let ((inhibit-read-only t)
(text (or text "» ")))
(save-excursion
(goto-char coil--prompt-start)
(delete-region (point) coil--input-start)
(insert (propertize text 'face 'coil-prompt 'read-only t 'field 'coil-prompt
'rear-nonsticky t 'front-sticky '(read-only)))
;; Typed text goes after the input marker, which stays put.
(set-marker coil--input-start (point)))
;; The prompt is inserted at its own start, which moved past it.
(set-marker coil--prompt-start (- coil--input-start (length text)))))
(defun coil--claim (beg end cell)
"Make BEG..END part of CELL: read-only, with the cell's keys."
(add-text-properties beg end `(coil-cell ,cell read-only t keymap ,coil-cell-map
front-sticky (read-only))))
(defun coil--note (session text &optional at)
"Put TEXT above the prompt of SESSION's buffer, or AT, a line of its own."
(with-current-buffer (coil--buffer session)
(let ((inhibit-read-only t))
(save-excursion
(goto-char (or at coil--prompt-start))
;; Before the markers there: a cell waiting at AT stays after its note.
(insert-before-markers (propertize (concat text "\n\n") 'face 'coil-header 'read-only t
'front-sticky '(read-only)))))))
(defun coil--fontify (code mode)
"CODE, fontified as MODE does, with `face' rather than `font-lock-face'."
(if (not (fboundp mode))
code
(with-temp-buffer
(insert code)
(delay-mode-hooks (funcall mode))
(font-lock-ensure)
(let ((pos (point-min)))
(while (< pos (point-max))
(let ((next (next-single-property-change pos 'font-lock-face nil (point-max)))
(face (get-text-property pos 'font-lock-face)))
(when face (put-text-property pos next 'face face))
(setq pos next))))
(buffer-string))))
(defun coil--header (cell)
(let* ((count (coil-cell-count cell))
(status (coil-cell-status cell))
(where (and (coil-cell-file cell)
(format " %s:%s" (file-name-nondirectory (coil-cell-file cell))
(coil-cell-line cell))))
(mark (pcase status
("ok" (propertize "✓" 'face 'coil-ok))
((or "error" "aborted") (propertize (if (equal status "error") "✗" "aborted")
'face 'coil-failed))
(_ "…")))
(time (and (coil-cell-duration cell)
(format " %.2f s" (coil-cell-duration cell)))))
;; Where it came from on the left; how it went at the right edge.
(let ((right (concat mark (if time (propertize time 'face 'coil-header) ""))))
(concat (propertize (format "In [%s]%s" (or count "*") (or where "")) 'face 'coil-header)
(propertize " " 'display `(space :align-to (- right ,(1+ (string-width right)))))
right))))
(defun coil--insert-cell (session cell)
"Put CELL in SESSION's buffer, above the prompt."
(with-current-buffer (coil--buffer session)
(let ((inhibit-read-only t)
(mode (plist-get (coil-session-backend session) :mode)))
(save-excursion
(goto-char coil--prompt-start)
(let ((beg (point)))
(insert (coil--header cell) "\n")
(let ((code (point)))
(insert (coil--fontify (string-trim-right (coil-cell-code cell)) mode) "\n")
(add-face-text-property code (point) 'coil-code t)
(coil--fold-input code (point)))
(let ((ostart (point)))
;; The cell ends with a hairline across the window.
(insert (propertize " " 'display '(space :align-to (- right 1)) 'face 'coil-rule)
"\n")
(setf (coil-cell-beg cell) (copy-marker beg)
(coil-cell-ostart cell) (copy-marker ostart)
(coil-cell-out cell) (copy-marker ostart t)))
(coil--claim beg (point) cell))))))
(defun coil--update-header (cell)
(when-let* ((beg (coil-cell-beg cell))
((marker-buffer beg)))
(with-current-buffer (marker-buffer beg)
(let ((inhibit-read-only t))
(save-excursion
(goto-char beg)
(delete-region (point) (line-end-position))
(insert (coil--header cell))
(coil--claim (line-beginning-position) (line-end-position) cell))))))
(defmacro coil--at-output (cell &rest body)
"Run BODY at the end of CELL's output, the inserted text claimed for it."
(declare (indent 1))
`(when-let* ((out (coil-cell-out ,cell))
((marker-buffer out)))
(with-current-buffer (marker-buffer out)
(let ((inhibit-read-only t)
(follow (cl-loop for window in (get-buffer-window-list nil nil t)
when (>= (window-point window) coil--input-start)
collect window)))
(save-excursion
(goto-char out)
(let ((beg (point)))
,@body
(coil--claim beg (point) ,cell)))
;; The prompt stays in view, the window scrolling no more than
;; that takes: nothing moves while it is in view.
(dolist (window follow)
(set-window-point window (point-max))
(unless (pos-visible-in-window-p (point-max) window)
(with-selected-window window
(goto-char (point-max))
(recenter -1))))))))
(defun coil--ansi (beg end)
"Colour BEG..END from its SGR sequences, and drop the other CSI ones.
The faces go in `face': this buffer has no font-lock."
(let ((ansi-color-apply-face-function
(lambda (b e face) (when face (put-text-property b e 'face face)))))
(ansi-color-apply-on-region beg end)))
(defun coil--insert-stream (cell text stderr)
(coil--at-output cell
(let ((text (string-replace "\r\n" "\n" text))
(first t))
(dolist (part (split-string text "\r"))
;; A carriage return writes over its line, as a progress bar does.
(unless first
(delete-region (max (line-beginning-position) (coil-cell-ostart cell)) (point)))
(setq first nil)
(let ((b (point)))
(insert part)
(coil--ansi b (point))
(when stderr (add-face-text-property b (point) 'coil-stderr t)))))))
(defun coil--png-pixels (data)
"The pixels of the PNG DATA says it is, from its header."
(when (and (> (length data) 24) (string-prefix-p "\x89PNG" data))
(cl-flet ((u32 (i) (+ (ash (aref data i) 24) (ash (aref data (+ i 1)) 16)
(ash (aref data (+ i 2)) 8) (aref data (+ i 3)))))
(* (u32 16) (u32 20)))))
(defun coil--save-image (session data type)
"Write the image DATA into SESSION's state, and return its file."
(let* ((dir (expand-file-name "img/" (coil-session-state session)))
(file (expand-file-name (concat (secure-hash 'sha1 data) "." (symbol-name type)) dir)))
(with-file-modes #o700 (make-directory dir t))
(unless (file-exists-p file)
(with-file-modes #o600
(let ((coding-system-for-write 'no-conversion))
(write-region data nil file nil 'silent))))
file))
(defun coil--image-width (buffer)
(let ((window (get-buffer-window buffer t)))
(min (or coil-image-max-width most-positive-fixnum)
(if window (- (window-body-width window t) 20) 800))))
(defun coil--insert-image (cell file)
(coil--at-output cell
(let ((image (create-image file nil nil :max-width (coil--image-width (current-buffer)))))
(insert-image image "[figure]")
(put-text-property (1- (point)) (point) 'coil-image file)
(insert "\n"))))
(defun coil--insert-text (cell text &optional prefix face)
(coil--at-output cell
(let ((b (point)))
(when prefix (insert (propertize prefix 'face 'coil-header)))
(let ((tb (point)))
(insert text)
(unless (bolp) (insert "\n"))
(coil--ansi tb (point))
(when face (add-face-text-property b (point) face t))))))
(defun coil--data (session cell data &optional count)
"Show DATA, a MIME bundle: its figure if it has one, else its text."
(let* ((png (alist-get 'image/png data))
(jpeg (alist-get 'image/jpeg data))
(text (alist-get 'text/plain data))
(prefix (and count (format "Out[%s]: " count))))
(cond
((or png jpeg)
(let* ((type (if png 'png 'jpeg))
(bytes (ignore-errors (base64-decode-string (or png jpeg))))
(pixels (and bytes (coil--png-pixels bytes))))
(cond ((not bytes)
(coil--insert-text cell "[an image that could not be decoded]\n" nil 'coil-failed))
((and pixels (> pixels coil-max-image-pixels))
(coil--insert-text cell (format "[an image of %d pixels, not drawn]\n" pixels)
nil 'coil-failed))
(t
(let ((file (coil--save-image session bytes type)))
(push `((type . "image") (file . ,(file-name-nondirectory file)))
(coil-cell-outputs cell))
(coil--insert-image cell file)
(run-hook-with-args 'coil-figure-functions session cell file))))))
(text
(push `((type . ,(if count "result" "text")) (text . ,text) (prefix . ,prefix))
(coil-cell-outputs cell))
(coil--insert-text cell text prefix)))))
(defun coil--clear-output (cell)
(coil--at-output cell
(delete-region (coil-cell-ostart cell) (point)))
(setf (coil-cell-outputs cell) nil))
(defun coil--cell-event (session cell kind event)
(when (and (coil-cell-clear-pending cell)
(member kind '("stream" "display" "result" "error")))
(setf (coil-cell-clear-pending cell) nil)
(coil--clear-output cell))
(pcase kind
("status"
(setf (coil-session-status session) (alist-get 'state event)))
("input"
;; It runs from now: the time before was spent waiting its turn.
(setf (coil-cell-count cell) (alist-get 'count event)
(coil-cell-start cell) (float-time))
(coil--update-header cell))
("stream"
(let ((stderr (equal (alist-get 'name event) "stderr"))
(text (alist-get 'text event)))
(push `((type . "stream") (name . ,(alist-get 'name event)) (text . ,text))
(coil-cell-outputs cell))
(coil--insert-stream cell text stderr)))
("display" (coil--data session cell (alist-get 'data event)))
("result" (coil--data session cell (alist-get 'data event) (alist-get 'count event)))
("error"
(let ((traceback (string-join (alist-get 'traceback event) "\n")))
(push `((type . "error") (ename . ,(alist-get 'ename event))
(evalue . ,(alist-get 'evalue event)) (traceback . ,traceback))
(coil-cell-outputs cell))
(coil--insert-text cell traceback)))
("clear"
(if (alist-get 'wait event)
(setf (coil-cell-clear-pending cell) t)
(coil--clear-output cell)))
("codefile"
(setf (coil-cell-codefile cell) (alist-get 'name event))
(puthash (alist-get 'name event) cell (coil-session-codefiles session)))
("done"
(remhash (alist-get 'id event) (coil-session-requests session))
(when (eq (car (coil-session-asking session)) cell)
(coil--stop-asking session))
(setf (coil-cell-status cell) (alist-get 'status event)
(coil-cell-duration cell) (- (float-time) (coil-cell-start cell)))
(when (alist-get 'count event)
(setf (coil-cell-count cell) (alist-get 'count event)))
(coil--update-header cell)
(coil--fold cell)
(coil--summarize cell)
(coil--log-cell session cell)
(run-hook-with-args 'coil-cell-done-functions session cell))))
(defun coil-show-cell (cell)
"Show CELL in its session buffer."
(when-let* ((beg (coil-cell-beg cell))
(buffer (marker-buffer beg)))
(pop-to-buffer buffer)
(goto-char beg)
(recenter 0)))
(defun coil--summarize (cell)
"Say how CELL went where it came from, if it was given a place (an overlay)."
(when-let* ((overlay (coil-cell-overlay cell))
((overlay-buffer overlay)))
(let* ((error (cl-find "error" (coil-cell-outputs cell)
:key (lambda (output) (alist-get 'type output)) :test #'equal))
(text (if (equal (coil-cell-status cell) "ok")
(propertize (format " ✓ %.2f s" (coil-cell-duration cell)) 'face 'coil-ok)
(propertize (format " ✗ %s"
(if error
(truncate-string-to-width
(format "%s: %s" (alist-get 'ename error)
(alist-get 'evalue error))
80 nil nil "…")
(coil-cell-status cell)))
'face 'coil-failed))))
(overlay-put overlay 'after-string
(propertize text 'mouse-face 'highlight 'help-echo "mouse-1: the output"
'keymap (define-keymap
"<mouse-1>" (lambda () (interactive) (coil-show-cell cell))))))))
(defun coil--make-fold (beg end label)
"Hide BEG..END, showing LABEL in its place; TAB shows it again."
(let ((overlay (make-overlay beg end)))
(overlay-put overlay 'invisible t)
(overlay-put overlay 'evaporate t) ; gone with its text
(overlay-put overlay 'coil-fold label)
(overlay-put overlay 'before-string label)
overlay))
(defun coil--fold-input (beg end)
"Fold the code from BEG to END (after its newline), if it is long."
(save-excursion
(goto-char beg)
(let ((lines (count-lines beg end)))
(when (and (> lines coil-fold-input-lines)
(zerop (forward-line coil-fold-input-shown)))
(coil--make-fold (point) (1- end)
(propertize (format "… %d more lines TAB"
(- lines coil-fold-input-shown))
'face '(coil-header coil-code)))))))
(defun coil--fold (cell)
"Fold CELL's output after `coil-fold-lines' lines."
(when-let* ((out (coil-cell-out cell))
((marker-buffer out)))
(with-current-buffer (marker-buffer out)
(save-excursion
(goto-char (coil-cell-ostart cell))
(when (and (zerop (forward-line coil-fold-lines))
(< (point) (1- out)))
(coil--make-fold (point) (1- out)
(propertize (format "… %d more lines TAB\n"
(count-lines (point) (1- out)))
'face 'coil-header)))))))
(defun coil-toggle-fold ()
"Show, or fold again, the long code or output of the cell at point."
(interactive)
(let* ((cell (or (get-text-property (point) 'coil-cell) (user-error "Not on a cell")))
(code-p (< (point) (coil-cell-ostart cell))))
(dolist (overlay (if code-p
(overlays-in (coil-cell-beg cell) (coil-cell-ostart cell))
(overlays-in (coil-cell-ostart cell) (coil-cell-out cell))))
(when-let* ((label (overlay-get overlay 'coil-fold)))
(let ((fold (not (overlay-get overlay 'invisible))))
(overlay-put overlay 'invisible fold)
(overlay-put overlay 'before-string (and fold label)))))))
;;; Running code
(cl-defun coil-execute (code &key file line origin session breakpoints)
"Run CODE in SESSION (this buffer's, started if need be).
FILE and LINE say where it came from, ORIGIN which of FILE's lines is the
first of CODE (LINE, if not given). It stops at BREAKPOINTS, a list as
`coil-breakpoints-function' returns, and at the latter's. Return the cell."
(let* ((session (or session (coil-current-session t)))
(cell (coil--cell-create :uid (format "%x-%x" (truncate (float-time)) (random 65536))
:code code :file file :line line
:origin (or origin line)
:start (float-time)))
(breakpoints (append breakpoints
(and coil-breakpoints-function
(funcall coil-breakpoints-function session cell)))))
(coil--insert-cell session cell)
(let ((id (apply #'coil--send session "execute" :code code
(and breakpoints (list :breakpoints (vconcat breakpoints))))))
(puthash id cell (coil-session-requests session)))
(unless (get-buffer-window (coil--buffer session) t)
(display-buffer (coil--buffer session)
'((display-buffer-reuse-window display-buffer-use-some-window
display-buffer-pop-up-window)
(inhibit-same-window . t))))
cell))
(defun coil--input-request (session cell event)
"Answer the kernel's `input()' from the minibuffer; C-g interrupts it.
Unless one of `coil-input-request-functions' takes the question."
(unless (and (not (alist-get 'password event))
(run-hook-with-args-until-success 'coil-input-request-functions
session cell event))
(let ((value (condition-case nil
(if (alist-get 'password event)
(read-passwd (alist-get 'prompt event))
(read-string (alist-get 'prompt event)))
(quit (coil--send session "interrupt") ""))))
(coil--send session "input" :value value)
(when (alist-get 'password event) (clear-string value)))))
(defun coil-ask (session cell prompt)
"Have the kernel's question, PROMPT, answered at SESSION's prompt.
The prompt becomes PROMPT; what is typed there next is the answer."
(setf (coil-session-asking session) (cons cell prompt))
(with-current-buffer (coil--buffer session)
(coil--insert-prompt (propertize prompt 'face 'coil-prompt))))
(defun coil--stop-asking (session)
(when (coil-session-asking session)
(setf (coil-session-asking session) nil)
(when (buffer-live-p (coil-session-buffer session))
(with-current-buffer (coil-session-buffer session)
(coil--insert-prompt)))))
(defun coil-answer (session value)
"Answer SESSION's question with VALUE, which is written under its cell."
(pcase-let ((`(,cell . ,prompt) (or (coil-session-asking session)
(user-error "The kernel asks nothing now"))))
(coil--stop-asking session)
(coil--insert-text cell (concat value "\n") prompt)
(push `((type . "stream") (name . "stdout") (text . ,(concat prompt value "\n")))
(coil-cell-outputs cell))
(coil--send session "input" :value value)))
(defun coil-interrupt (&optional restart)
"Interrupt what the kernel is running.
With RESTART (\\[universal-argument]), restart the kernel instead, losing its state."
(interactive "P")
(if restart
(coil-restart)
(coil--send (or (coil-current-session) (user-error "No session")) "interrupt")))
(defun coil-detach ()
"Let go of the kernel, which runs on: C-c C-z, or any send, attaches again."
(interactive)
(let ((session (or (coil-current-session) (user-error "Not attached"))))
(setf (coil-session-status session) "detached")
(delete-process (coil-session-process session))
(coil--note session "Detached: the kernel runs on. C-c C-z, or any send, attaches again.")
(coil--refresh-mode-line session)))
(defun coil-restart ()
"Shut the kernel down, and start a new one."
(interactive)
(let ((session (coil-current-session t)))
(when (y-or-n-p "Restart the kernel, losing its state? ")
(setf (coil-session-status session) "restarting")
;; Sent once the bridge is ready, if it is not yet.
(coil--send session "shutdown")
(let ((until (+ (float-time) 30)))
(while (and (process-live-p (coil-session-process session))
(< (float-time) until))
(accept-process-output (coil-session-process session) 0.1)))
(coil--start (coil-session-root session) (coil-session-backend session) session))))
(defun coil-shutdown ()
"Shut the kernel down: its state is lost; the log is kept."
(interactive)
(when-let* ((session (coil-current-session)))
(when (y-or-n-p "Shut the kernel down, losing its state? ")
(setf (coil-session-status session) "shut down")
(coil--send session "shutdown"))))
;;; Input
(defun coil--in-input-p ()
(and coil--input-start (>= (point) coil--input-start)))
(defun coil--input ()
(buffer-substring-no-properties coil--input-start (point-max)))
(defun coil-beginning-of-line ()
"To the start of the input on its first line, else of the line."
(interactive)
(if (and (coil--in-input-p)
(<= (line-beginning-position) coil--input-start))
(goto-char coil--input-start)
(move-beginning-of-line 1)))
(defun coil-return ()
"Run the input if it is complete, else start a new line; on a cell, visit it."