-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
jupyter-repl.el
2179 lines (1959 loc) · 91.6 KB
/
jupyter-repl.el
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
;;; jupyter-repl-client.el --- A Jupyter REPL client -*- lexical-binding: t -*-
;; Copyright (C) 2018-2024 Nathaniel Nicandro
;; Author: Nathaniel Nicandro <nathanielnicandro@gmail.com>
;; Created: 08 Jan 2018
;; 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, 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; A Jupyter REPL for Emacs.
;;
;; The main entry points are `jupyter-run-repl' and `jupyter-connect-repl'.
;;
;; When called interactively, `jupyter-run-repl' asks for a kernel to
;; start, connects a `jupyter-repl-client' to the selected kernel, and
;; pops up a REPL buffer. The main difference of
;; `jupyter-connect-repl' is that it will obtain the kernel's
;; connection info by asking for the JSON file containing it to start
;; connection to a kernel.
;;
;; Additionally, `jupyter-repl-associate-buffer' associates the
;; `current-buffer' with a REPL client appropriate for the buffer's
;; `major-mode'. Associating a buffer with a REPL client enables the minor
;; mode `jupyter-repl-interaction-mode'.
;;
;; `jupyter-repl-interaction-mode' adds the following keybindings for
;; interacting with a REPL client:
;;
;; C-c C-c `jupyter-eval-line-or-region'
;; C-c C-l `jupyter-eval-file'
;; M-i `jupyter-inspect-at-point'
;; C-c C-r `jupyter-repl-restart-kernel'
;; C-c C-i `jupyter-repl-interrupt-kernel'
;; C-c C-z `jupyter-repl-pop-to-buffer'
;;; Code:
(defgroup jupyter-repl nil
"A Jupyter REPL client"
:group 'jupyter)
(eval-when-compile (require 'subr-x))
(eval-and-compile (require 'jupyter-client))
(require 'jupyter-base)
(require 'jupyter-mime)
(require 'jupyter-kernelspec)
(require 'jupyter-widget-client)
(require 'ring)
(declare-function jupyter-notebook-process "jupyter-server")
(declare-function jupyter-launch-notebook "jupyter-server")
(declare-function jupyter-server "jupyter-server")
;;; User variables
(defface jupyter-repl-input-prompt
'((((class color) (min-colors 88) (background light))
:foreground "darkseagreen2")
(((class color) (min-colors 88) (background dark))
:foreground "darkolivegreen"))
"Face used for the input prompt."
:group 'jupyter-repl)
(defface jupyter-repl-output-prompt
'((((class color) (min-colors 88) (background light))
:foreground "indianred3")
(((class color) (min-colors 88) (background dark))
:foreground "darkred"))
"Face used for the output prompt."
:group 'jupyter-repl)
(defface jupyter-repl-traceback
'((((class color) (min-colors 88) (background light))
:background "LightYellow2")
(((class color) (min-colors 88) (background dark))
:background "firebrick"))
"Face used for a traceback."
:group 'jupyter-repl)
(defcustom jupyter-repl-maximum-size 1024
"Maximum number of lines before the buffer is truncated."
:type 'integer
:group 'jupyter-repl)
(defcustom jupyter-repl-maximum-is-complete-timeout 2
"Maximum number of seconds to wait for an is-complete reply.
When no is-complete reply is received from the kernel within this
timeout, the built-in is-complete handler is used."
:type 'integer
:group 'jupyter-repl)
(defcustom jupyter-repl-history-maximum-length 100
"The maximum number of history elements to keep track of."
:type 'integer
:group 'jupyter-repl)
(defcustom jupyter-repl-prompt-margin-width 12
"The width of the margin which displays prompt strings."
:type 'integer
:group 'jupyter-repl)
(defcustom jupyter-repl-cell-pre-send-hook nil
"Hook run before sending the contents of an input cell to a kernel.
The hook is run with `point' at the cell code beginning position
and before the contents of the cell are extracted from the buffer
for sending to the kernel."
:type 'hook
:group 'jupyter-repl)
(defcustom jupyter-repl-cell-post-send-hook nil
"Hook run after sending the contents of an input cell to a kernel.
The hook is run with `point' at the cell code beginning
position."
:type 'hook
:group 'jupyter-repl)
(defcustom jupyter-repl-allow-RET-when-busy nil
"Allow RET to insert a newline when the kernel is busy.
Normally when the kernel is busy, pressing RET at an input cell
is disallowed. This is because, when the kernel is busy, it does
not respond to an `:is-complete-request' message and that message
is used to avoid sending incomplete code to the kernel.
If this variable is non-nil, RET is allowed to insert a newline.
In this case, pressing RET on an empty line, i.e. RET RET, will
send the code to the kernel."
:type 'boolean
:group 'jupyter-repl)
(defcustom jupyter-repl-echo-eval-p nil
"Copy evaluation input to a REPL cell if non-nil.
If non-nil, and when calling the `jupyter-eval-*' functions like
`jupyter-eval-line-or-region', copy the input into a REPL cell.
Otherwise the evaluation request is sent to the kernel without
displaying the code of the request in the REPL.
Note, output generated by requests will always be sent to the
REPL buffer whenever this variable is non-nil. When the REPL
buffer isn't visible, output will also be sent to pop-up buffers
as is done when this variable is nil."
:type 'boolean
:group 'jupyter-repl)
(defcustom jupyter-repl-completion-at-point-hook-depth nil
"The DEPTH of `jupyter-completion-at-point' in `completion-at-point-functions'.
`completion-at-point-functions' hooks are tried in order. A value of nil for
this variable means `jupyter-completion-at-point' will be added to the head of
the list, which means it will be tried first on completion attempts. This might
prevent other hooks like `lsp-completion-at-point' from running.
If you'd prefer to give `jupyter-completion-at-point' lower priority, set this
variable to something like 1. Check `add-hook' documentation for more details
about DEPTH."
:type 'integer
:group 'jupyter-repl)
;;; Implementation
(defclass jupyter-repl-client (jupyter-widget-client jupyter-kernel-client)
((buffer
:type (or null buffer)
:initform nil
:documentation "The REPL buffer whose
`jupyter-current-client' is this client.")
(wait-to-clear
:type boolean
:initform nil
:documentation "Whether or not we should wait to clear the
current output of the cell. Set when the kernel sends a
`:clear-output' message.")))
(defvar-local jupyter-repl-lang-buffer nil
"A buffer with the `major-mode' set to the REPL language's `major-mode'.")
(defvar-local jupyter-repl-lang-mode nil
"The `major-mode' corresponding to the REPL's language.")
(defvar-local jupyter-repl-history nil
"The history of the current Jupyter REPL.")
(defvar-local jupyter-repl-use-builtin-is-complete nil
"Whether or not to send `:is-complete-request's to a kernel.
If a Jupyter kernel does not respond to an is_complete_request,
the buffer local value of this variable is set to t and code in a
cell is considered complete if the last line in a code cell is a
blank line, i.e. if RET is pressed twice in a row.")
(cl-generic-define-context-rewriter jupyter-repl-mode (mode &rest modes)
`(jupyter-repl-lang-mode (derived-mode ,mode ,@modes)))
;;; Macros
(defmacro jupyter-with-repl-buffer (client &rest body)
"Switch to CLIENT's REPL buffer and evaluate BODY.
`inhibit-read-only' is let bound to t while evaluating
BODY. After evaluation, if the current buffer is visible in some
window, set the window point to the value of `point' in the
buffer."
(declare (indent 1) (debug (symbolp &rest form)))
`(with-current-buffer (oref ,client buffer)
(let ((inhibit-read-only t))
(prog1 (progn ,@body)
(let ((win (get-buffer-window)))
(when win (set-window-point win (point))))))))
(defvar jupyter-repl-inhibit-continuation-prompts nil
"Non-nil when continuation prompts are suppressed.
See `jupyter-repl-insert-continuation-prompts'.")
(defmacro jupyter-repl-without-continuation-prompts (&rest body)
"Evaluate BODY without inserting continuation prompts."
(declare (debug (&rest form)))
`(let ((jupyter-repl-inhibit-continuation-prompts t))
,@body))
(defmacro jupyter-repl-append-output (client req &rest body)
"Switch to CLIENT's buffer, move to the end of REQ, and evaluate BODY.
REQ is a `jupyter-request' previously made using CLIENT, a REPL
client.
`point' is moved to the `jupyter-repl-cell-beginning-position' of
the cell *after* REQ, this position is where any newly generated
output of REQ should be inserted.
Also handles any terminal control codes in the appended output."
(declare (indent 2) (debug (symbolp &rest form)))
`(jupyter-with-repl-buffer ,client
(let ((buffer-undo-list t))
(save-excursion
(jupyter-repl-goto-cell ,req)
(jupyter-repl-next-cell)
(jupyter-with-insertion-bounds
beg end (jupyter-with-control-code-handling ,@body)
(put-text-property beg end 'read-only t)
(set-buffer-modified-p nil))))))
(defmacro jupyter-with-repl-lang-buffer (&rest body)
"Evaluate BODY in the `jupyter-repl-lang-buffer' of the `current-buffer'.
The contents of `jupyter-repl-lang-buffer' is erased before
evaluating BODY."
(declare (indent 0) (debug (&rest form)))
(let ((client (make-symbol "clientvar")))
`(let ((,client jupyter-current-client))
(with-current-buffer jupyter-repl-lang-buffer
(let ((inhibit-read-only t)
(jupyter-current-client ,client))
(erase-buffer)
,@body)))))
(defmacro jupyter-with-repl-cell (&rest body)
"Narrow to the current cell, evaluate BODY, then widen.
The cell is narrowed to the region between and including
`jupyter-repl-cell-code-beginning-position' and
`jupyter-repl-cell-code-end-position'."
(declare (indent 0) (debug (&rest form)))
`(save-excursion
(save-restriction
(narrow-to-region (jupyter-repl-cell-code-beginning-position)
(jupyter-repl-cell-code-end-position))
,@body)))
(defmacro jupyter-repl-with-single-undo (&rest body)
"Evaluate BODY, remove all undo boundaries created during its evaluation."
(declare (indent 0) (debug (&rest form)))
(let ((handle (make-symbol "handle")))
`(let ((,handle (prepare-change-group)))
(unwind-protect
(progn
(activate-change-group ,handle)
,@body)
(undo-amalgamate-change-group ,handle)
(accept-change-group ,handle)))))
;;; Text insertion
(defun jupyter-repl-newline ()
"Insert a read-only newline into the `current-buffer'."
(insert (propertize "\n" 'read-only t)))
(cl-defmethod jupyter-insert :around (mime-or-plist
&context (major-mode jupyter-repl-mode) &rest _ignore)
"If MIME was inserted, mark the region that was inserted as read only.
Do this only when the `major-mode' is `jupyter-repl-mode'."
(if (listp mime-or-plist) (cl-call-next-method)
(jupyter-with-insertion-bounds
beg end (cl-call-next-method)
(add-text-properties beg end '(read-only t)))))
(cl-defmethod jupyter-insert ((_mime (eql :application/vnd.jupyter.widget-view+json)) data
&context ((and (require 'websocket nil t)
(require 'simple-httpd nil t)
(and jupyter-current-client
(object-of-class-p
jupyter-current-client
'jupyter-widget-client))
t)
(eql t))
&optional _metadata)
(jupyter-widgets-display-model jupyter-current-client (plist-get data :model_id)))
;;; Util
(defun jupyter-repl-completing-read-repl-buffer (&optional mode)
"Return a REPL buffer, selecting from all available ones.
Return nil if no REPL buffers are available.
MODE has the same meaning as in
`jupyter-repl-available-repl-buffers'."
(when-let* ((buffers (jupyter-repl-available-repl-buffers mode))
(names (mapcar #'buffer-name buffers))
(buffer (completing-read "REPL buffer: " names nil t)))
(when (equal buffer "")
(error "No REPL buffer selected"))
(get-buffer buffer)))
;;; Prompt
(defconst jupyter-repl-input-prompt-format "In [%d] ")
(defconst jupyter-repl-output-prompt-format "Out [%d] ")
(defconst jupyter-repl-busy-prompt "In [*] ")
(defsubst jupyter-repl--prompt-string (ov)
(nth 0 (overlay-get ov 'jupyter-prompt)))
(defsubst jupyter-repl--prompt-face (ov)
(nth 1 (overlay-get ov 'jupyter-prompt)))
(defun jupyter-repl--prompt-margin-alignment (str)
(- jupyter-repl-prompt-margin-width (length str)))
(defun jupyter-repl--prompt-display-value (str face)
"Return the margin display value for a prompt STR.
FACE is the `font-lock-face' to use for STR."
(list '(margin left-margin)
(propertize
(concat
(make-string (jupyter-repl--prompt-margin-alignment str) ?\s) str)
'fontified t
'font-lock-face face)))
(defun jupyter-repl--reset-prompt-display (ov)
(when-let* ((prompt (jupyter-repl--prompt-string ov))
(face (or (jupyter-repl--prompt-face ov)
'jupyter-repl-input-prompt))
(md (jupyter-repl--prompt-display-value prompt face)))
(overlay-put ov 'after-string (propertize " " 'display md))))
(defun jupyter-repl--reset-prompts ()
"Re-calculate all prompt strings in the buffer.
Also set the local value of `left-margin-width' to
`jupyter-repl-prompt-margin-width'."
(setq-local left-margin-width jupyter-repl-prompt-margin-width)
(dolist (ov (overlays-in (point-min) (point-max)))
(jupyter-repl--reset-prompt-display ov)))
(defun jupyter-repl--make-prompt (str face props)
"Make a prompt overlay for the character before POS.
STR is used as the prompt string and FACE is its
`font-lock-face'. Add PROPS as text properties to the character."
(when (< (jupyter-repl--prompt-margin-alignment str) 0)
(setq-local jupyter-repl-prompt-margin-width
(+ jupyter-repl-prompt-margin-width
(abs (jupyter-repl--prompt-margin-alignment str))))
(jupyter-repl--reset-prompts))
(let ((ov (make-overlay (1- (point)) (point) nil t)))
(overlay-put ov 'jupyter-prompt (list str face))
(overlay-put ov 'evaporate t)
(jupyter-repl--reset-prompt-display ov)
(add-text-properties (overlay-start ov) (overlay-end ov) props)
(overlay-recenter (point))))
(defun jupyter-repl-insert-prompt (&optional type count)
"Insert a REPL prompt according to TYPE.
TYPE can either be `in', `out', or `continuation'. A nil TYPE is
interpreted as `in'.
When TYPE is `in' and COUNT is a number, insert a prompt with a
count equal to COUNT. For TYPE `in' and COUNT not a number, the
execution-count of the `jupyter-current-client' will be used as
count. COUNT is ignored otherwise."
(setq type (or type 'in))
(unless (memq type '(in out continuation))
(error "Prompt type can only be (`in', `out', or `continuation')"))
(jupyter-repl-without-continuation-prompts
(let ((inhibit-read-only t))
;; The newline that `jupyter-repl--make-prompt' will overlay.
(insert (propertize "\n" 'read-only (not (eq type 'continuation))))
(cond
((eq type 'in)
(let ((count (if (numberp count) count
(oref jupyter-current-client execution-count))))
(jupyter-repl--make-prompt
(format jupyter-repl-input-prompt-format count)
'jupyter-repl-input-prompt
`(jupyter-cell (beginning ,count))))
;; Prevent prompt overlay from inheriting text properties of code at the
;; beginning of a cell.
;;
;; The rear-nonsticky property prevents code inserted after
;; this character from inheriting any of this character's text
;; properties.
;;
;; The front-sticky property prevents `point' from being
;; trapped between the newline of the prompt overlay and this
;; invisible character.
(insert (propertize " "
'read-only t 'invisible t
'rear-nonsticky t 'front-sticky t))
;; The insertion of a new prompt starts a new cell, don't consider the
;; buffer modified anymore. This is also an indicator for when undo's
;; can be made in the buffer.
(set-buffer-modified-p nil)
(setq buffer-undo-list '((t . 0))))
((eq type 'out)
;; Output is normally inserted by first going to the end of the output
;; for the request. The end of the ouput for a request is at the
;; beginning of the next cell after the request which is why we get the
;; cell count of the previous cell
(let ((count (jupyter-repl-previous-cell-count)))
(jupyter-repl--make-prompt
(format jupyter-repl-output-prompt-format count)
'jupyter-repl-output-prompt
`(jupyter-cell (out ,count))))
;; See the note above about the invisible character for input prompts
(insert (propertize " " 'read-only t 'invisible t 'front-sticky t)))
((eq type 'continuation)
(jupyter-repl--make-prompt
;; This needs to be two characters wide for some
;; reason, otherwise the continuation prompts will
;; be missing one character.
" " 'jupyter-repl-input-prompt
`(read-only nil rear-nonsticky t)))))))
(defun jupyter-repl-prompt-string ()
"Return the prompt string of the current input cell."
(jupyter-repl--prompt-string
(car (overlays-at (jupyter-repl-cell-beginning-position)))))
(defun jupyter-repl-cell-reset-prompt ()
"Reset the current prompt back to its default."
(jupyter-repl-cell-update-prompt
(format jupyter-repl-input-prompt-format (jupyter-repl-cell-count))))
(defun jupyter-repl-cell-update-prompt (str &optional face)
"Update the current cell's input prompt.
STR is the replacement prompt string. If FACE is non-nil, it
should be a face that the prompt will use and defaults to
`jupyter-repl-input-prompt'."
(when-let* ((ov (car (overlays-at (jupyter-repl-cell-beginning-position)))))
(overlay-put ov 'jupyter-prompt (list str face))
(jupyter-repl--reset-prompt-display ov)))
(defun jupyter-repl-cell-mark-busy ()
"Mark the current cell as busy."
(when (equal (jupyter-repl-prompt-string)
(format jupyter-repl-input-prompt-format
(jupyter-repl-cell-count)))
(jupyter-repl-cell-update-prompt jupyter-repl-busy-prompt)))
(defun jupyter-repl-cell-unmark-busy ()
"Un-mark the current cell as busy."
(when (equal (jupyter-repl-prompt-string) jupyter-repl-busy-prompt)
(jupyter-repl-cell-update-prompt
(format jupyter-repl-input-prompt-format
(jupyter-repl-cell-count)))))
(defun jupyter-repl-update-cell-count (n)
"Set the current cell count to N."
(when (or (jupyter-repl-cell-beginning-p)
(zerop (save-excursion (jupyter-repl-previous-cell))))
(setf (nth 1 (get-text-property
(jupyter-repl-cell-beginning-position)
'jupyter-cell))
n)
(when (string-match-p "In \\[[0-9]+\\]" (jupyter-repl-prompt-string))
(jupyter-repl-cell-reset-prompt))))
(defun jupyter-repl-cell-count ()
"Return the cell count of the cell at `point'."
(let ((pos (if (jupyter-repl-cell-beginning-p) (point)
(save-excursion
(jupyter-repl-previous-cell)
(point)))))
(nth 1 (get-text-property pos 'jupyter-cell))))
(defun jupyter-repl-previous-cell-count ()
"Return the cell count of the previous cell before `point'."
(save-excursion
(jupyter-repl-previous-cell)
(jupyter-repl-cell-count)))
(defun jupyter-repl-cell-request ()
"Return the `jupyter-request' of the current cell."
(get-text-property (jupyter-repl-cell-beginning-position) 'jupyter-request))
;;; Cell motions
(defun jupyter-repl-cell-beginning-position ()
"Return the cell beginning position of the current cell.
If `point' is already at the beginning of the current cell,
return `point'.
If the end of a cell is found before the beginning of one, i.e.
when `point' is somewhere inside the output of a cell, raise an
error.
If the beginning of the buffer is found before the beginning of a
cell, raise a `beginning-of-buffer' error."
(let ((pos (point)))
(while (not (jupyter-repl-cell-beginning-p pos))
(setq pos (previous-single-property-change pos 'jupyter-cell))
(if pos (when (jupyter-repl-cell-end-p pos)
(error "Found end of previous cell"))
(if (jupyter-repl-cell-beginning-p (point-min))
(setq pos (point-min))
(signal 'beginning-of-buffer nil))))
pos))
(defun jupyter-repl-cell-end-position ()
"Return the cell ending position of the current cell.
This is similar to `jupyter-repl-cell-beginning-position' except
the position at the end of the current cell is returned and an
error is raised if the beginning of a cell is found before an
end.
Note: If the current cell is the last cell in the buffer,
`point-max' is considered the end of the cell."
(let ((pos (point)))
(catch 'unfinalized
(while (not (jupyter-repl-cell-end-p pos))
(setq pos (next-single-property-change pos 'jupyter-cell))
(if pos (when (jupyter-repl-cell-beginning-p pos)
(error "Found beginning of next cell"))
;; Any unfinalized cell must be at the end of the buffer.
(throw 'unfinalized (point-max))))
pos)))
(defun jupyter-repl-cell-code-beginning-position ()
"Return the beginning of the current cell's code.
The code beginning position is
`jupyter-repl-cell-beginning-position' + 2
There is an extra invisible character after the prompt."
(+ (jupyter-repl-cell-beginning-position) 2))
(defun jupyter-repl-cell-code-end-position ()
"Return the end of the current cell's code.
In the case of the last cell in the REPL buffer, i.e. an
unfinalized cell, the code ending position is `point-max'."
(jupyter-repl-cell-end-position))
(defun jupyter-repl-next-cell (&optional N)
"Go to the beginning of the next cell.
Move N times where N defaults to 1. Return the count of cells
left to move."
(or N (setq N 1))
(catch 'done
(while (> N 0)
(let ((pos (next-single-property-change (point) 'jupyter-cell)))
(while (and pos (not (jupyter-repl-cell-beginning-p pos)))
(setq pos (next-single-property-change pos 'jupyter-cell)))
(unless (when pos (goto-char pos) (setq N (1- N)))
(goto-char (point-max))
(throw 'done t)))))
N)
(defun jupyter-repl-previous-cell (&optional N)
"Go to the beginning of the previous cell.
Move N times where N defaults to 1. Return the count of cells
left to move.
Note, if `point' is not at the beginning of the current cell, the
first move is to the beginning of the current cell."
(or N (setq N 1))
(catch 'done
(let ((starting-pos (point)))
(while (> N 0)
(let ((pos (previous-single-property-change (point) 'jupyter-cell)))
(while (and pos (not (jupyter-repl-cell-beginning-p pos)))
(setq pos (previous-single-property-change pos 'jupyter-cell)))
(unless (when pos (goto-char pos) (setq N (1- N)))
(goto-char (point-min))
;; Handle edge case when the first cell is at the beginning of the
;; buffer. This happens, for example, when erasing the buffer.
(when (and (/= (point) starting-pos)
(jupyter-repl-cell-beginning-p (point)))
(setq N (1- N)))
(throw 'done t))))))
N)
(defun jupyter-repl-goto-cell (req)
"Go to the cell beginning position of REQ.
REQ should be a `jupyter-request' associated with a cell in the
`current-buffer'. Note that the `current-buffer' is assumed to
be a Jupyter REPL buffer."
(goto-char (point-max))
(unless (catch 'done
(while (= (jupyter-repl-previous-cell) 0)
(when (eq (jupyter-repl-cell-request) req)
(throw 'done t))))
(error "Cell for request not found")))
(defun jupyter-repl-forward-cell (&optional arg)
"Go to the code beginning of the cell after the current one.
ARG is the number of cells to move and defaults to 1."
(interactive "^p")
(or arg (setq arg 1))
(jupyter-repl-next-cell arg)
(goto-char (jupyter-repl-cell-code-beginning-position)))
(defun jupyter-repl-backward-cell (&optional arg)
"Go to the code beginning of the cell before the current one.
ARG is the number of cells to move and defaults to 1."
(interactive "^p")
(or arg (setq arg 1))
;; Ignore the case when `point' is in the output of a cell, in this case
;; `jupyter-repl-previous-cell' will go to the previous cell.
(ignore-errors (goto-char (jupyter-repl-cell-beginning-position)))
(jupyter-repl-previous-cell arg)
(goto-char (jupyter-repl-cell-code-beginning-position)))
(defun jupyter-repl-map-cells (beg end input output)
"Call INPUT or OUTPUT on the corresponding cells between BEG and END.
For every input or output cell between BEG and END, call INPUT or
OUTPUT, respectively, with the buffer narrowed to the cell.
INPUT and OUTPUT are functions of no arguments.
Note the narrowed regions may not be full input/output cells if
BEG and END are within an input/output cell."
(declare (indent 2))
(save-excursion
(save-restriction
(let (next)
(while (/= beg end)
(widen)
(cond
((eq (get-text-property beg 'field) 'cell-code)
(setq next (min end (field-end beg t)))
(narrow-to-region beg next)
(funcall input))
(t
(setq next (or (text-property-any
beg end 'field 'cell-code)
end))
(narrow-to-region beg next)
(funcall output)))
(setq beg next))))))
;;; Predicates
(defun jupyter-repl-cell-beginning-p (&optional pos)
"Is POS the beginning of a cell?
POS defaults to `point'."
(setq pos (or pos (point)))
(eq (nth 0 (get-text-property pos 'jupyter-cell)) 'beginning))
(defun jupyter-repl-cell-end-p (&optional pos)
"Is POS the end of a cell?
POS defaults to `point'."
(setq pos (or pos (point)))
(or (= pos (point-max))
(eq (nth 0 (get-text-property pos 'jupyter-cell)) 'end)))
(defun jupyter-repl-multiline-p (text)
"Is TEXT a multi-line string?"
(string-match-p "\n" text))
(defun jupyter-repl-cell-line-p ()
"Is the current line a cell input line?"
(let ((pos (point)))
(ignore-errors
(save-excursion
(unless (= pos (jupyter-repl-cell-beginning-position))
(jupyter-repl-previous-cell))
(<= (jupyter-repl-cell-code-beginning-position)
pos
(jupyter-repl-cell-code-end-position))))))
(defun jupyter-repl-cell-finalized-p ()
"Has the current cell been finalized?"
(or (not (jupyter-repl-cell-line-p))
(/= (jupyter-repl-cell-end-position) (point-max))))
(defun jupyter-repl-connected-p ()
"Is the `jupyter-current-client' connected to its kernel?"
(and jupyter-current-client
(jupyter-connected-p jupyter-current-client)))
;;; Modifying cell code, truncating REPL buffer
(defun jupyter-repl-cell-output ()
"Return the output of the current cell."
(unless (jupyter-repl-cell-finalized-p)
(error "Cell not finalized"))
(let ((beg (jupyter-repl-cell-end-position))
(end (save-excursion
(jupyter-repl-next-cell)
(jupyter-repl-cell-beginning-position))))
(buffer-substring beg end)))
(defun jupyter-repl-cell-code ()
"Return the code of the current cell."
(buffer-substring
(jupyter-repl-cell-code-beginning-position)
(jupyter-repl-cell-code-end-position)))
(defun jupyter-repl-cell-code-position ()
"Return the relative position of `point' with respect to the cell code."
(unless (jupyter-repl-cell-line-p)
(error "Not in code of cell"))
(1+ (- (point) (jupyter-repl-cell-code-beginning-position))))
(defun jupyter-repl-finalize-cell (req)
"Finalize the current input cell.
REQ is the `jupyter-request' to associate with the current cell.
Place `point' at `point-max'."
(goto-char (point-max))
(let ((beg (jupyter-repl-cell-beginning-position))
(count (jupyter-repl-cell-count)))
(jupyter-repl-newline)
(put-text-property (1- (point)) (point) 'jupyter-cell `(end ,count))
(put-text-property beg (1+ beg) 'jupyter-request req)
;; Remove this property so that text can't be inserted at the start of the
;; cell or after any continuation prompts. See
;; `jupyter-repl-insert-prompt'.
(remove-text-properties beg (point) '(rear-nonsticky))
(add-text-properties beg (point) '(read-only t))
;; reset the undo list so that a completed cell doesn't get undone.
(setq buffer-undo-list '((t . 0)))))
(defun jupyter-repl-replace-cell-code (new-code)
"Replace the current cell code with NEW-CODE.
If NEW-CODE is a buffer use `replace-buffer-contents' to replace
the cell code. Otherwise NEW-CODE should be a string, the current
cell code will be erased and NEW-CODE inserted in its place."
(if (bufferp new-code)
(jupyter-with-repl-cell
(jupyter-repl-with-single-undo
;; Need to create a single undo step here because
;; `replace-buffer-contents' adds in unwanted undo boundaries.
;;
;; Tests failing on Appveyor due to `replace-buffer-contents' not
;; supplying the right arguments to `after-change-functions' so call
;; the change functions manually. Seen on Emacs 26.1.
;;
;; For reference see https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32278
(let ((inhibit-modification-hooks t)
(beg (point-min))
(end (point-max))
(new-len (with-current-buffer new-code
(- (point-max) (point-min)))))
(run-hook-with-args
'before-change-functions beg end)
(replace-buffer-contents new-code)
(run-hook-with-args
'after-change-functions
beg (+ beg new-len) (- end beg)))))
(goto-char (jupyter-repl-cell-code-beginning-position))
(delete-region (point) (jupyter-repl-cell-code-end-position))
(insert-and-inherit new-code)))
(defun jupyter-repl-truncate-buffer ()
"Truncate the `current-buffer' based on `jupyter-repl-maximum-size'.
The `current-buffer' is assumed to be a Jupyter REPL buffer. If
the `current-buffer' is larger than `jupyter-repl-maximum-size'
lines, truncate it to something less than
`jupyter-repl-maximum-size' lines."
(save-excursion
(when (= (forward-line (- jupyter-repl-maximum-size)) 0)
(jupyter-repl-next-cell)
(delete-region (point-min) (point)))))
(defun jupyter-repl-clear-cells ()
"Clear the input and output cells of the current buffer."
(interactive)
(jupyter-repl-without-continuation-prompts
(let ((inhibit-read-only t))
(save-excursion
(goto-char (point-min))
(when (get-text-property (point) 'jupyter-banner)
(goto-char (next-single-property-change (point) 'jupyter-banner)))
(delete-region (point) (point-max))
(jupyter-repl-insert-prompt 'in))))
(goto-char (point-max)))
(defun jupyter-repl-clear-input ()
"Clear the contents of the input cell."
(interactive)
(goto-char (point-max))
(delete-region
(jupyter-repl-cell-code-beginning-position)
(point-max)))
;;; Handlers
(defun jupyter-repl-history-add (code)
"Add CODE as the newest element in the REPL history."
;; Ensure the newest element is actually the newest element and not the most
;; recently navigated history element.
(while (not (eq (ring-ref jupyter-repl-history -1) 'jupyter-repl-history))
(ring-insert jupyter-repl-history (ring-remove jupyter-repl-history)))
;; Remove the second to last element when the ring is full to preserve the
;; sentinel.
(when (eq (ring-length jupyter-repl-history)
(ring-size jupyter-repl-history))
(ring-remove jupyter-repl-history -2))
(ring-remove+insert+extend jupyter-repl-history code))
(defun jupyter-repl-execute-cell (&optional client)
"Execute the last REPL cell of CLIENT.
Return the `jupyter-request' representing the executed code."
(or client (setq client jupyter-current-client))
(cl-check-type client jupyter-repl-client)
(jupyter-with-repl-buffer client
(jupyter-repl-truncate-buffer)
(save-excursion
(goto-char (jupyter-repl-cell-code-beginning-position))
(run-hooks 'jupyter-repl-cell-pre-send-hook))
(let ((code (string-trim (jupyter-repl-cell-code) "[\r\n]+")))
(jupyter-run-with-client client
(jupyter-mlet* ((req (jupyter-execute-request
:code code
;; Handle empty code cells as just an update
;; of the prompt number
:silent (and (= (length code) 0) t))))
(jupyter-repl-without-continuation-prompts
(jupyter-repl-cell-mark-busy)
(jupyter-repl-finalize-cell req)
(jupyter-repl-history-add code)
(jupyter-repl-insert-prompt
'in (1+ (oref client execution-count))))
(save-excursion
(jupyter-repl-backward-cell)
(run-hooks 'jupyter-repl-cell-post-send-hook))
(jupyter-sent (jupyter-return req)))))))
(cl-defmethod jupyter-handle-payload ((_source (eql set_next_input)) pl
&context (major-mode jupyter-repl-mode))
(goto-char (point-max))
(jupyter-repl-previous-cell)
(jupyter-repl-replace-cell-code (plist-get pl :text)))
(cl-defmethod jupyter-handle-execute-reply ((client jupyter-repl-client) _req msg)
(jupyter-with-repl-buffer client
(jupyter-with-message-content msg (payload)
(when payload
(jupyter-handle-payload payload)))))
(cl-defmethod jupyter-handle-execute-result ((client jupyter-repl-client) req msg)
;; Only handle our results
(when req
(jupyter-repl-append-output client req
(jupyter-repl-insert-prompt 'out)
(jupyter-with-message-content msg (data metadata)
(jupyter-insert data metadata)))))
(cl-defmethod jupyter-handle-display-data ((client jupyter-repl-client) req msg)
(let ((clear (prog1 (oref client wait-to-clear)
(oset client wait-to-clear nil)))
(req (if (equal (jupyter-message-parent-type msg) "comm_msg")
;; For comm messages which produce a display_data message,
;; the request is assumed to be the most recently completed
;; one.
(jupyter-with-repl-buffer client
(save-excursion
(goto-char (point-max))
(jupyter-repl-previous-cell 2)
(jupyter-repl-cell-request)))
req)))
(jupyter-repl-append-output client req
(jupyter-with-message-content msg (data metadata transient)
(cl-destructuring-bind (&key display_id &allow-other-keys)
transient
(if display_id
(jupyter-insert display_id data metadata)
(let ((inhibit-redisplay (not debug-on-error)))
(when clear
(jupyter-repl-clear-last-cell-output client)
;; Prevent slight flickering of prompt margin and text, this is
;; needed in addition to `inhibit-redisplay'. It also seems that
;; it can be placed anywhere within this let and it will prevent
;; flickering.
(sit-for 0.1 t))
(jupyter-insert data metadata))))))))
(cl-defmethod jupyter-handle-update-display-data ((client jupyter-repl-client) _req msg)
(jupyter-with-message-content msg (data metadata transient)
(cl-destructuring-bind (&key display_id &allow-other-keys)
transient
(unless display_id
(error "No display ID in `update_display_data' message"))
(jupyter-with-repl-buffer client
(jupyter-update-display display_id data metadata)))))
(defun jupyter-repl-clear-last-cell-output (client)
"In CLIENT's REPL buffer, clear the output of the last completed cell."
(jupyter-with-repl-buffer client
(goto-char (point-max))
(jupyter-repl-previous-cell 2)
(delete-region (1+ (jupyter-repl-cell-end-position))
(progn
(jupyter-repl-next-cell)
(point)))))
(cl-defmethod jupyter-handle-clear-output ((client jupyter-repl-client) _req msg)
(unless (oset client wait-to-clear
(jupyter-with-message-content msg (wait)
(eq wait t)))
(cond
((equal (jupyter-message-parent-type msg) "comm_msg")
(with-current-buffer (jupyter-get-buffer-create "output")
(erase-buffer)))
(t
(jupyter-repl-clear-last-cell-output client)))))
(cl-defmethod jupyter-handle-status ((client jupyter-repl-client) req msg)
(when (equal "idle"
(jupyter-with-message-content msg (execution_state)
execution_state))
(jupyter-with-repl-buffer client
(save-excursion
(when (ignore-errors
(progn (jupyter-repl-goto-cell req) t))
(jupyter-repl-cell-unmark-busy))
;; Update the cell count and reset the prompt
(goto-char (point-max))
(jupyter-repl-update-cell-count (oref client execution-count)))))
(force-mode-line-update))
(defun jupyter-repl-display-other-output (client stream text)
"Display output not originating from CLIENT.
STREAM is the name of a stream which will be used to select the
buffer to display TEXT."
(let* ((bname (buffer-name (oref client buffer)))
(stream-buffer
(concat (substring bname 0 (1- (length bname))) "-" stream "*")))
;; FIXME: Reset this on the next request
(jupyter-with-display-buffer stream-buffer nil
(let ((pos (point)))
(jupyter-insert-ansi-coded-text text)
(fill-region pos (point)))
(jupyter-display-current-buffer-reuse-window))))
(cl-defmethod jupyter-handle-stream ((client jupyter-repl-client) req msg)
(jupyter-with-message-content msg (name text)
(if (null req)
(jupyter-repl-display-other-output client name text)
(cond
((equal (jupyter-message-parent-type
(jupyter-request-last-message req))
"comm_msg")
(jupyter-with-display-buffer "output" req
(jupyter-insert-ansi-coded-text text)
(jupyter-display-current-buffer-reuse-window)))
(t
(jupyter-repl-append-output client req
(jupyter-insert-ansi-coded-text text)))))))
(cl-defmethod jupyter-handle-error ((client jupyter-repl-client) req msg)
(when req
(jupyter-with-message-content msg (traceback)
(cond
((equal (jupyter-message-parent-type msg) "comm_msg")
(jupyter-display-traceback traceback))
(t
(jupyter-repl-append-output client req
(jupyter-with-insertion-bounds
beg end (jupyter-insert-ansi-coded-text
(concat (mapconcat #'identity traceback "\n") "\n"))
(font-lock-prepend-text-property
beg end 'font-lock-face 'jupyter-repl-traceback))))))))
(defun jupyter-repl-history--rotate (n)
"Rotate the REPL history ring N times.
The direction of rotation is determined by the sign of N. For N
positive rotate to newer history elements, for N negative rotate
to older elements.
Return nil if the sentinel value is found before completing the
required number of rotations, otherwise return the element
rotated to, i.e. the one at index 0."
(let (ifun cidx ridx)
(if (> n 0)