forked from jkitchin/scimax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscimax-org-babel-ipython-upstream.el
1596 lines (1364 loc) · 57.3 KB
/
scimax-org-babel-ipython-upstream.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
;;; scimax-org-babel-ipython-upstream.el --- Modifications to the upstream ob-ipython module -*- lexical-binding: t; -*-
;;; Commentary:
;; This file contains monkey patches and enhancements to the upstream ob-ipython
;; module. Several new customizations are now possible.
;;
;; Some new header arguments:
;;
;; :display can be used to specify which mime-types are displayed. The default is all of them.
;; :restart can be used to restart the kernel before executing the cell
;; :async is not new, but it works by itself now, and causes an asynchronous evaluation of the cell
(require 'scimax-ob)
;; * Customizations
;;; Code:
(defcustom ob-ipython-eldoc-integration nil
"If non-nil use eldoc to show signatures."
:group 'ob-ipython)
(defcustom ob-ipython-buffer-unique-kernel t
"If non-nil use a unique kernel for each buffer."
:group 'ob-ipython)
(defcustom ob-ipython-show-mime-types t
"If non-nil show mime-types in output."
:group 'ob-ipython)
(defcustom ob-ipython-exception-results t
"If non-nil put the contents of the traceback buffer as results."
:group 'ob-ipython)
(defcustom ob-ipython-suppress-execution-count nil
"Deprecated. See `ob-ipython-execution-count'.
If non-nil do not show the execution count in output."
:group 'ob-ipython)
(defcustom ob-ipython-execution-count
#'ob-ipython-execution-count-output
"Function for showing the execution count.
The function takes one argument, the execution count. It should return a string to be displayed. Use an empty string to suppress the count.
`ob-ipython-execution-count-suppress' will not show anything.
`ob-ipython-execution-count-output' will show a string in the ouput.
`ob-ipython-execution-count-overlay' will show an overlay in the margin.
`ob-ipython-execution-count-attribute' will store it in a src-block attribute."
:group 'ob-ipython
:type 'function)
(defcustom ob-ipython-count-overlay-width 11
"Width of the left-margin fringe for the execution count overlays."
:group 'ob-ipython
:type 'number)
(defcustom ob-ipython-kill-kernel-on-exit t
"If non-nil, prompt user to kill kernel when killing a buffer."
:group 'ob-ipython)
(defcustom ob-ipython-delete-stale-images t
"If non-nil remove images that will be replaced."
:group 'ob-ipython)
(defcustom ob-ipython-mime-formatters
'((text/plain . ob-ipython-format-text/plain)
(text/html . ob-ipython-format-text/html)
(text/latex . ob-ipython-format-text/latex)
(text/org . ob-ipython-format-text/org)
(image/png . ob-ipython-format-image/png)
(image/svg+xml . ob-ipython-format-image/svg+xml)
(application/javascript . ob-ipython-format-application/javascript)
(default . ob-ipython-format-default)
(output . ob-ipython-format-output))
"An alist of (mime-type . format-func) for mime-types.
Each function takes two arguments, which is file-or-nil and a
string to be formatted."
:group 'ob-ipython)
(defcustom ob-ipython-plain-text-filter-regexps
'(
;this is what boring python objects look like. I never need to see these, so
;we strip them out. That might be a strong opinion though, and might
;surprise people who like to or are used to seeing them.
"^<.*at 0x.*>"
)
"A list of regular expressions to filter out of text/plain results."
:group 'ob-ipython)
(defcustom ob-ipython-key-bindings
'(("<return>" . #'newline-and-indent)
("C-<return>" . #'org-ctrl-c-ctrl-c)
("M-<return>" . (lambda () (interactive) (scimax-execute-and-next-block t)))
("S-<return>" . #'scimax-execute-and-next-block)
("M-S-<return>" . #'scimax-execute-to-point)
("s-<return>" . #'scimax-ob-ipython-restart-kernel-execute-block)
("M-s-<return>" . #'scimax-restart-ipython-and-execute-to-point)
("H-<return>" . #'scimax-ob-ipython-restart-kernel-execute-buffer)
("H-k" . #'scimax-ob-ipython-kill-kernel)
("H-r" . #'org-babel-switch-to-session)
;; navigation commands
("s-i" . #'org-babel-previous-src-block)
("s-k" . #'org-babel-next-src-block)
("H-q" . #'scimax-jump-to-visible-block)
("H-s-q" . #'scimax-jump-to-block)
;; editing commands
("H-=" . #'scimax-insert-src-block)
("H--" . #'scimax-split-src-block)
("H-n" . #'scimax-ob-copy-block-and-results)
("H-w" . #'scimax-ob-kill-block-and-results)
("H-o" . #'scimax-ob-clone-block)
("s-w" . #'scimax-ob-move-src-block-up)
("s-s" . #'scimax-ob-move-src-block-down)
("H-l" . #'org-babel-remove-result)
("H-s-l" . #'scimax-ob-clear-all-results)
("H-m" . #'scimax-merge-ipython-blocks)
("H-h" . #'scimax-ob-edit-header)
("H-M-l" . #'scimax-ob-toggle-line-numbers)
("s-." . #'scimax-ob-ipython-complete-ivy)
("s-/" . #'ob-ipython-inspect)
;; the jupyter hydras
("H-e" . #'scimax-jupyter-edit-mode/body)
("H-c" . #'scimax-jupyter-command-mode/body)
;; The hydra/popup menu
("H-s" . #'scimax-obi/body)
("<mouse-3>" . #'scimax-ob-ipython-popup-command))
"An alist of key bindings and commands.
These are activated in function `ob-ipython-key-bindings'."
:group 'ob-ipython)
(defcustom ob-ipython-menu-items
'(("Execute"
["Current block" org-ctrl-c-ctrl-c t]
["Current and next" scimax-execute-and-next-block t]
["To point" scimax-execute-to-point t]
["Restart/block" scimax-ob-ipython-restart-kernel-execute-block t]
["Restart/to point" scimax-restart-ipython-and-execute-to-point t]
["Restart/buffer" scimax-ob-ipython-restart-kernel-execute-buffer t])
("Edit"
["Move block up" scimax-ob-move-src-block-up t]
["Move block down" scimax-ob-move-src-block-down t]
["Kill block" scimax-ob-kill-block-and-results t]
["Copy block" scimax-ob-copy-block-and-results t]
["Clone block" scimax-ob-clone-block t]
["Split block" scimax-split-src-block t]
["Clear result" org-babel-remove-result t]
["Edit header" scimax-ob-edit-header t]
["Toggle line numbers" scimax-ob-toggle-line-numbers t])
("Navigate"
["Previous block" org-babel-previous-src-block t]
["Next block" (lambda ()
(interactive)
(org-babel-next-src-block))
t]
["Jump to visible block" scimax-jump-to-visible-block t]
["Jump to block" scimax-jump-to-block t])
["Inspect" ob-ipython-inspect t]
["Show source" (lambda ()
(interactive)
(ob-ipython-inspect))
t]
["Kill kernel" scimax-ob-ipython-kill-kernel t]
["Switch to repl" org-babel-switch-to-session t])
"Items for the menu bar and popup menu."
:group 'ob-ipython)
(defcustom ob-ipython-buttons
'(("<run>" org-ctrl-c-ctrl-c "Click to run")
("<restart and run>" scimax-ob-ipython-restart-kernel-execute-block "click to restart and run")
("<repl>" org-babel-switch-to-session "Click to open repl")
("<interrupt>" ob-ipython-interrupt-kernel "Click to interrupt")
("<delete block>" scimax-ob-kill-block-and-results "kill block")
("<menu>" scimax-ob-ipython-popup-command "Popup menu")
("<output>" (lambda () (interactive)
(pop-to-buffer "*ob-ipython-out*")) "open output buffer")
("<debug>" (lambda () (interactive)
(pop-to-buffer "*ob-ipython-debug*")) "open debug buffer")
("<execute>" (lambda () (interactive)
(pop-to-buffer "*ob-ipython-execute*")) "open execute buffer"))
"A list of (text cmd help) to make clickable buttons.
text is regexp/string that will become a button.
cmd is run when you click on the button.
help is a string for a tooltip."
:group 'ob-ipython)
(defcustom ob-ipython-html-to-image-program
(executable-find "wkhtmltoimage")
"Path to wkhtmltoimage, and any additional options you want."
:group 'ob-ipython)
(unless ob-ipython-html-to-image-program
(warn "No wkhtmltoimage found. Either set `ob-ipython-html-to-image-program' to the location, or go to https://wkhtmltopdf.org/downloads.html to get and install it."))
(defcustom ob-ipython-preview-html t
"if non-nil try previewing html."
:group 'ob-ipython)
(defcustom ob-ipython-preview-html-size 800
"Size in pixels to make the html previews."
:group 'ob-ipython)
(defun ob-ipython-key-bindings ()
"Function to define key-bindings.
Usually called in a hook function."
(cl-loop for cell in ob-ipython-key-bindings
do
(eval `(scimax-define-src-key ipython ,(car cell) ,(cdr cell)))))
(add-hook 'org-mode-hook 'ob-ipython-key-bindings t)
;; * org templates and default header args
;; org 9.2 changed this variable in a backwards incompatible way. I think I do
;; all of these through yasnippet now, so I am going to just comment these out
;; for now, in case I want to add them to a snippet later.
;; (add-to-list 'org-structure-template-alist
;; '("ip" "#+BEGIN_SRC ipython\n?\n#+END_SRC"
;; "<src lang=\"python\">\n?\n</src>"))
;; (add-to-list 'org-structure-template-alist
;; '("ipv" "#+BEGIN_SRC ipython :results value\n?\n#+END_SRC"
;; "<src lang=\"python\">\n?\n</src>"))
;; (add-to-list 'org-structure-template-alist
;; '("plt" "%matplotlib inline\nimport matplotlib.pyplot as plt\n?"
;; ""))
;; (add-to-list 'org-structure-template-alist
;; '("np" "import numpy as np\n?"
;; ""))
;; (add-to-list 'org-structure-template-alist
;; '("anp" "import autograd.numpy as np\n?"
;; ""))
(setq org-babel-default-header-args:ipython
'((:results . "output replace drawer")
(:session . "ipython")
(:exports . "both")
(:cache . "no")
(:noweb . "no")
(:hlines . "no")
(:tangle . "no")
(:eval . "never-export")))
(defun scimax-install-ipython-lexer ()
"Install the IPython lexer for Pygments.
You need this to get syntax highlighting."
(interactive)
(unless (= 0
(shell-command
"python -c \"import pygments.lexers; pygments.lexers.get_lexer_by_name('ipython')\""))
(shell-command "pip install git+git://github.com/sanguineturtle/pygments-ipython-console")))
;; * A hydra for ob-ipython blocks
(defhydra scimax-obi (:color blue :hint nil)
"
Execute Navigate Edit Misc
-----------------------------------------------------------------------------------------------------------------------------
_<return>_: current _i_: previous _w_: move up _._: inspect _<up>_:
_S-<return>_: current to next _k_: next _s_: move down _l_: clear result _<left>_: _<right>_:
_S-M-<return>_: to point _q_: visible _x_: kill _L_: clear all _<down>_:
_s-<return>_: Restart/block _Q_: any _n_: copy _,_: complete
_M-s-<return>_: Restart/to point _C-<up>_: goto start _c_: clone _o_: toggle result folding
_H-<return>_: Restart/buffer _C-<down>_: goto end _m_: merge
_K_: kill kernel _C-<left>_: word left _-_: split
_r_: Goto repl _C-<right>_: word right _+_: insert above
^ ^ ^ ^ _=_: insert below
^ ^ ^ ^ _h_: header
_[_: dedent _]_: indent _3_: toggle comment _z_: undo _y_: redo
Convert
------------------------------------------------------------------
_y_: to code
_M_: to markdown
_O_: to org
markdown headings _1_: _2_: _3_: _4_: _5_: _6_:
"
("o" ob-ipython-toggle-output :color red)
("<up>" ob-ipython-edit-up :color red)
("<down>" ob-ipython-edit-down :color red)
("<left>" left-char :color red)
("<right>" right-char :color red)
("C-<up>" ob-ipython-jump-to-first-line)
("C-<down>" ob-ipython-jump-to-end-line)
("C-<left>" left-word :color red)
("C-<right>" right-word :color red)
;; These don't really have great analogs in org-mode, but maybe it makes sense
;; to be able to do this.
("y" (ob-ipython-convert-block-to "ipython"))
("M" (ob-ipython-convert-block-to "markdown"))
("O" (ob-ipython-convert-block-to "org"))
;; These change to markdown block and trim blank lines off the top and add #
;; to beginning
("1" (ob-ipython-markdown-headings 1))
("2" (ob-ipython-markdown-headings 2))
("3" (ob-ipython-markdown-headings 3))
("4" (ob-ipython-markdown-headings 4))
("5" (ob-ipython-markdown-headings 5))
("6" (ob-ipython-markdown-headings 6))
("z" undo-tree-undo :color red)
("y" undo-tree-redo :color red)
("[" (progn
(org-edit-special)
(python-indent-line t)
(org-edit-src-exit)) :color red)
("]" (progn
(org-edit-special)
(python-indent-line)
(org-edit-src-exit)) :color red)
("<return>" org-ctrl-c-ctrl-c :color red)
("S-<return>" scimax-execute-and-next-block :color red)
("S-M-<return>" scimax-execute-to-point)
("s-<return>" scimax-ob-ipython-restart-kernel-execute-block)
("M-s-<return>" scimax-restart-ipython-and-execute-to-point)
("H-<return>" scimax-ob-ipython-restart-kernel-execute-buffer)
("K" scimax-ob-ipython-kill-kernel)
("r" org-babel-switch-to-session)
("i" org-babel-previous-src-block :color red)
("k" org-babel-next-src-block :color red)
("q" scimax-jump-to-visible-block)
("Q" scimax-jump-to-block)
("w" scimax-ob-move-src-block-up :color red)
("s" scimax-ob-move-src-block-down :color red)
("x" scimax-ob-kill-block-and-results)
("n" scimax-ob-copy-block-and-results)
("c" scimax-ob-clone-block)
("m" scimax-merge-ipython-blocks)
("-" scimax-split-src-block)
("+" scimax-insert-src-block)
("=" (scimax-insert-src-block t))
("l" org-babel-remove-result)
("L" scimax-ob-clear-all-results)
("h" scimax-ob-edit-header)
("3" org-comment-dwim :color red)
("." ob-ipython-inspect)
("," scimax-ob-ipython-complete-ivy))
;; * command/edit-mode hydra
;;These hydras are to mimic as closely as possible the Jupyter keybindings.
(defun ob-ipython-convert-block-to (type)
"Convert current block to TYPE.
TYPE is usually one of ipython, markdown, org
Note: you will lose header arguments from this."
(interactive (list (completing-read "Type: " '(ipython markdown org))))
(let* ((src-info (or (org-babel-get-src-block-info t)
(org-babel-lob-get-info)))
(header-start (sixth src-info))
(header-end (save-excursion (goto-char header-start)
(line-end-position))))
(setf (buffer-substring header-start header-end)
(format "#+BEGIN_SRC %s" type))))
(defun ob-ipython-markdown-headings (N)
"Convert block to markdown and set first line to heading level N."
(interactive "nLevel: ")
(ob-ipython-convert-block-to "markdown")
(save-restriction
(org-narrow-to-block)
(goto-char (point-min))
(forward-line)
(delete-trailing-whitespace)
(while (looking-at "^$") (delete-char 1))
(insert (make-string N ?#))
(insert " ")))
(defun ob-ipython-toggle-output ()
"Toggle folded state of results if there are some."
(interactive)
(let ((loc (org-babel-where-is-src-block-result)))
(when loc
(save-excursion
(goto-char loc)
(org-cycle)))))
(defun ob-ipython-jump-to-first-line ()
"Move point to start of first line in the src block."
(interactive)
(org-edit-special)
(goto-char (point-min))
(org-edit-src-exit))
(defun ob-ipython-jump-to-end-line ()
"Move point to end of last line in the src block."
(org-edit-special)
(goto-char (point-max))
(org-edit-src-exit))
(defun ob-ipython-mark-code ()
"Mark the code in the block."
(interactive)
(org-edit-special)
(let ((p0 (point-min))
(p1 (point-max)))
(goto-char p0)
(org-edit-src-exit)
(set-mark (point))
(goto-char (+ (point) (- p1 2)))))
(defun ob-ipython-merge-next-cell ()
"Merge current cell with next one."
(interactive)
(let ((r1 (point))
(r2 (save-excursion (org-babel-next-src-block) (point))))
(scimax-merge-ipython-blocks r1 r2)))
;; https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/
(defhydra scimax-jupyter-edit-mode (:color blue :hint nil)
"
Execute Edit Navigate
-----------------------------------------------------------------------------------------
_C-<return>_: run cell _[_: dedent _C-<up>_: goto start _<up>_:
_S-<return>_: run cell and next _]_: indent _C-<down>_: goto end _<left>_: _<right>_:
_M-<return>_: run cell and new _-_: split cell _C-<left>_: word left _<down>_:
^ ^ _/_: toggle comment _C-<right>_: word right
^ ^ _a_: select cell
_c_: command mode _z_: undo _y_: redo
"
("[" (python-indent-line t) "dedent" :color red)
("]" (python-indent-line) "indent" :color red)
("a" ob-ipython-mark-code "select all")
("z" undo-tree-undo "undo")
("y" undo-tree-redo "redo")
;; I don't have a <home> or <end> on my mac keyboard...
;; ("<home>" ob-ipython-jump-to-first-line "goto cell start")
;; ("C-<end>" ob-ipython-jump-to-end-line "goto cell end")
("<up>" ob-ipython-edit-up "move cursor up or previous cell" :color red)
("<down>" ob-ipython-edit-down "move cursor down or next cell" :color red)
("<left>" left-char "move cursor left" :color red)
("<right>" right-char "move cursor right" :color red)
("C-<up>" ob-ipython-jump-to-first-line "goto cell start")
("C-<down>" ob-ipython-jump-to-end-line "goto cell end")
("C-<left>" left-word "one word left" :color red)
("C-<right>" right-word "one word right" :color red)
;; We can't use esc for command mode
("c" scimax-jupyter-command-mode/body "command mode")
("C-<return>" org-ctrl-c-ctrl-c "run cell" :color red)
("S-<return>" scimax-execute-and-next-block "run cell, select below" :color red)
("M-<return>" (scimax-execute-and-next-block t) "run cell, insert new" :color red)
("-" scimax-split-src-block"split cell")
("/" org-comment-dwim "toggle comment on current or selected lines" :color red))
(defun ob-ipython-edit-up ()
"Move to previous line, unless at the top.
In that case first move to beginning of line, and then move to
previous cell."
(interactive)
(let ((first-code-line-p (save-excursion
(forward-line -1)
(beginning-of-line)
(looking-at "#\\+BEGIN_SRC"))))
(cond
((and (bolp) first-code-line-p)
(ignore-errors
(catch 'block
(while (org-babel-previous-src-block)
(when (string= "ipython"
(org-element-property :language (org-element-context)))
(throw 'block t))))))
(first-code-line-p
(beginning-of-line))
(t
(previous-line)))))
(defun ob-ipython-edit-down ()
"Move to next line, unless at the bottom.
In that case first move to beginning of line, and then move to
previous cell."
(interactive)
(let ((last-code-line-p (save-excursion
(forward-line 1)
(beginning-of-line)
(looking-at "#\\+END_SRC"))))
(cond
((and (eolp) last-code-line-p)
(ignore-errors
(catch 'block
(while (org-babel-next-src-block)
(when (string= "ipython"
(org-element-property :language (org-element-context)))
(throw 'block t))))))
(last-code-line-p
(end-of-line))
(t
(next-line)))))
;; https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/
(defhydra scimax-jupyter-command-mode (:color blue :hint nil)
"
Navigate Execute Edit Misc
-----------------------------------------------------------------------------------------------------------
_<up>_: previous cell _C-<return>_: run cell _a_: insert cell above _l_: toggle line numbers
_k_: previous cell _S-<return>_: run cell/next _b_: insert below _o_: toggle result folding
_<down>_: next cell _M-<return>_: run cell/next _x_: cut cell _ii_: interrupt kernel
_j_: next cell ^ ^ _V_: copy above _0_: restart kernel
^ ^ ^ ^ _v_: copy below _<SPC>_: scroll down
^ ^ ^ ^ _dd_: delete cell _S-<SPC>_: scroll up
^ ^ ^ ^ _M_: merge next
Convert
------------------------------------------------------------------
_y_: to code
_m_: to markdown
_r_: to org
markdown headings _1_: _2_: _3_: _4_: _5_: _6_:
_s_: save buffer _z_: undo _<return>_: edit mode
"
("<return>" scimax-jupyter-edit-mode/body "Enter edit mode")
("C-<return>" org-ctrl-c-ctrl-c "run cell" :color red)
("S-<return>" scimax-execute-and-next-block "run cell, select next" :color red)
("M-<return>" (scimax-execute-and-next-block t) "run cell, insert new" :color red)
;; These don't really have great analogs in org-mode, but maybe it makes sense
;; to be able to do this.
("y" (ob-ipython-convert-block-to "ipython") "to code")
("m" (ob-ipython-convert-block-to "markdown") "to markdown")
("r" (ob-ipython-convert-block-to "org") "to raw")
;; These change to markdown block and trim blank lines off the top and add #
;; to beginning
("1" (ob-ipython-markdown-headings 1) "to heading 1")
("2" (ob-ipython-markdown-headings 2) "to heading 2")
("3" (ob-ipython-markdown-headings 3) "to heading 3")
("4" (ob-ipython-markdown-headings 4) "to heading 4")
("5" (ob-ipython-markdown-headings 5) "to heading 5")
("6" (ob-ipython-markdown-headings 6) "to heading 6")
;; navigation
("<up>" org-babel-previous-src-block "select cell above" :color red)
("k" org-babel-previous-src-block "select cell above" :color red)
("<down>" org-babel-next-src-block "select cell below" :color red)
("j" org-babel-next-src-block "select cell below" :color red)
("a" scimax-insert-src-block "insert cell above")
("b" (scimax-insert-src-block t) "insert cell below")
("x" scimax-ob-kill-block-and-results "cut cell")
("V" (scimax-ob-clone-block t) "paste cell above")
("v" scimax-ob-clone-block "paste cell below")
("z" undo "undo last cell deletion" :color red)
("dd" scimax-ob-kill-block-and-results "delete cell")
;; need a new function to select region from point to next one.
("M" ob-ipython-merge-next-cell "merge cell below")
;; I am not sure we can do this with a kernel
;; ("C-s" "save and checkpoint")
("s" save-buffer "Save buffer")
("l" scimax-ob-toggle-line-numbers "toggle line numbers" :color red)
;; this folds output
("o" ob-ipython-toggle-output "toggle output" :color red)
;; for large ouputs, puts results in a window you can scroll in. Not sure if
;; that is possible in emacs. May be no analog.
;; ( ;; "S-o" "toggle output scrolling"
;; )
;; Maybe no analog?
;; ("esc" "close pager")
;; ("h" "Show keyboard help")
("ii" ob-ipython-interrupt-kernel "Interrupt kernel")
;; 00 is not a good hydra command
("0" (when (y-or-n-p "Restart kernel? ")
(call-interactively 'ob-ipython-kill-kernel)) "restart kernel")
;; Emacs has the opposite scroll convention as a browser
("<SPC>" scroll-up-command "scroll down" :color red)
("S-<SPC>" scroll-down-command "scroll up" :color red))
;; * A context menu
(define-prefix-command 'scimax-ob-ipython-mode-map)
(easy-menu-define ob-ipython-menu scimax-ob-ipython-mode-map "ob-ipython menu"
ob-ipython-menu-items)
(defun ob-ipython-org-menu ()
"Add the ob-ipython menu to the Org menu."
(easy-menu-change '("Org") "ob-ipython" ob-ipython-menu-items "Show/Hide")
(easy-menu-change '("Org") "--" nil "Show/Hide"))
(add-hook 'org-mode-hook 'ob-ipython-org-menu)
(defun scimax-ob-ipython-popup-command (event)
"Popup a menu of actions for src blocks."
(interactive "e")
(popup-menu (append '("ob-ipython") ob-ipython-menu-items)))
;; * Execution functions
(defun scimax-ob-ipython-default-session ()
"Return the default name of the session for a src block."
(concat
;; this is the block language
(car (or (org-babel-get-src-block-info t) (org-babel-lob-get-info)))
"-"
(if-let (bf (buffer-file-name))
(md5 (expand-file-name bf))
"scratch")))
(defun scimax-ob-ipython-restart-kernel-execute-block ()
"Restart kernel and execute block."
(interactive)
(ob-ipython-kill-kernel
(cdr (assoc (scimax-ob-ipython-default-session )
(ob-ipython--get-kernel-processes))))
(org-babel-execute-src-block-maybe))
(defun scimax-ob-ipython-restart-kernel-execute-buffer ()
"Restart kernel and execute buffer."
(interactive)
(ob-ipython-kill-kernel
(cdr (assoc (scimax-ob-ipython-default-session)
(ob-ipython--get-kernel-processes))))
(org-babel-execute-buffer))
(defun scimax-restart-ipython-and-execute-to-point ()
"Kill the kernel and run src-blocks to point."
(interactive)
(call-interactively 'ob-ipython-kill-kernel)
(scimax-execute-to-point))
(defun scimax-ob-ipython-kill-kernel ()
"Kill the active kernel."
(interactive)
(when (and (not (s-contains? "*temp*" (buffer-name))) (y-or-n-p "Kill kernel? "))
(ob-ipython-kill-kernel
(cdr (assoc (scimax-ob-ipython-default-session)
(ob-ipython--get-kernel-processes))))
(setq header-line-format nil)
(redisplay)
;; clean up some buffers
(loop for buf in (list
"ob-ipython-out*" "*ob-ipython-debug*"
"*ob-ipython-kernel-ipython*"
(format "*ob-ipython-kernel-%s*" (scimax-ob-ipython-default-session))
(format "*Python:%s" (scimax-ob-ipython-default-session)))
do
(when (get-buffer buf)
(kill-buffer buf)))))
;; * block editing functions
(defun scimax-merge-ipython-blocks (r1 r2)
"Merge blocks in the current region (R1 R2).
This deletes the results from each block, and concatenates the
code into a single block in the position of the first block.
Currently no switches/parameters are preserved. It isn't clear
what the right thing to do for those is, e.g. dealing with
variables, etc."
(interactive "r")
;; Expand the region to encompass the src blocks that the points might be in.
(let* ((R1 (save-excursion
(goto-char r1)
(if (org-in-src-block-p)
(org-element-property :begin (org-element-context))
r1)))
(R2 (save-excursion
(goto-char r2)
(if (org-in-src-block-p)
(org-element-property :end (org-element-context))
r2))))
(save-restriction
(narrow-to-region R1 R2)
(let* ((blocks (org-element-map (org-element-parse-buffer) 'src-block
(lambda (src)
(when (string= "ipython" (org-element-property :language src))
src))))
(first-start (org-element-property :begin (car blocks)))
(merged-code (s-join "\n" (loop for src in blocks
collect
(org-element-property :value src)))))
;; Remove blocks
(loop for src in (reverse blocks)
do
(goto-char (org-element-property :begin src))
(org-babel-remove-result)
(setf (buffer-substring (org-element-property :begin src)
(org-element-property :end src))
""))
;; Now create the new big block.
(goto-char first-start)
(insert (format "#+BEGIN_SRC ipython
%s
#+END_SRC\n\n" (s-trim merged-code)))))))
;; * Modifications of ob-ipython
;; I frequently get an error on startup that seems to be related to how long
;; jupyter takes to start up. Usually, I just run the cell again and it works.
;; This modification is designed to wait just long enough for the json file to
;; get created. This seems to fix the issue. It used to wait just 1 second, but
;; sometimes it takes up to two seconds to create this file (it is used in
;; driver.py I think).
(defcustom scimax-create-kernel-max-wait 5
"Maximum seconds to wait before kernel program starts."
:group 'ob-ipython)
(defun ob-ipython--create-kernel (name &optional kernel)
(when (and (not (ignore-errors (process-live-p (get-process (format "kernel-%s" name)))))
(not (s-ends-with-p ".json" name)))
(ob-ipython--create-process
(format "kernel-%s" name)
(append
(list ob-ipython-command "console" "--simple-prompt")
(list "-f" (ob-ipython--kernel-file name))
(if kernel (list "--kernel" kernel) '())
;;should be last in the list of args
ob-ipython-kernel-extra-args))
(let ((i 0)
(t0 (float-time))
(tincrement 0.1)
(cfile (expand-file-name
(ob-ipython--kernel-file name)
(s-trim (shell-command-to-string "jupyter --runtime-dir")))))
(while (and (not (file-exists-p cfile))
(< (- (float-time) t0) scimax-create-kernel-max-wait))
(sleep-for tincrement))
(message "Kernel started in %1.2f seconds" (- (float-time) t0))
(setq header-line-format name))))
(defun ob-ipython-kill-kernel (proc)
"Kill a kernel process.
If you then re-evaluate a source block a new kernel will be started."
(interactive (ob-ipython--choose-kernel))
(when proc
(let* ((proc-name (process-name proc))
(proc-buffer (format "*ob-ipython-%s*" proc-name))
(cfile (expand-file-name
(format "%s.json" (s-replace "kernel-" "emacs-" proc-name))
(s-trim (shell-command-to-string "jupyter --runtime-dir")))))
(when (f-exists? cfile)
(f-delete cfile))
(delete-process proc)
(kill-buffer (process-buffer proc))
(setq header-line-format nil)
(message (format "Killed %s and deleted %s" proc-name cfile)))))
;; Modified to make buffer unique kernels automatically
(defun org-babel-execute:ipython (body params)
"Execute a block of IPython code with Babel.
This function is called by `org-babel-execute-src-block'."
;; make sure we get prompted to kill the kernel when exiting.
(when ob-ipython-kill-kernel-on-exit
(add-hook 'kill-buffer-hook 'scimax-ob-ipython-kill-kernel nil t))
(when (and
;; if these are equal, we use default, if not user defined session
;; unless they just used :session
(not (null (cdr (assoc :session
(third (or (org-babel-get-src-block-info t)
(org-babel-lob-get-info)))))))
(eq (assoc :session org-babel-default-header-args:ipython)
(assoc :session (third (or (org-babel-get-src-block-info t)
(org-babel-lob-get-info)))))
;; we want unique kernels
ob-ipython-buffer-unique-kernel)
(make-local-variable 'org-babel-default-header-args:ipython)
;; remove the old session info
(setq org-babel-default-header-args:ipython
(remove (assoc :session org-babel-default-header-args:ipython)
org-babel-default-header-args:ipython))
;; add the new session info
(let ((session-name (scimax-ob-ipython-default-session)))
(add-to-list 'org-babel-default-header-args:ipython
(cons :session session-name))
(setf (cdr (assoc :session params)) session-name)))
(ob-ipython--clear-output-buffer)
;; delete any figures that will be replaced and clear results here.
(when ob-ipython-delete-stale-images
(let ((result-string (let ((location (org-babel-where-is-src-block-result)))
(when location
(save-excursion
(goto-char location)
(when (looking-at (concat org-babel-result-regexp ".*$"))
(buffer-substring-no-properties
(save-excursion
(skip-chars-backward " \r\t\n")
(line-beginning-position 2))
(progn (forward-line) (org-babel-result-end))))))))
(files '())
;; This matches automatic file generation
(fregex "\\[\\[file:\\(obipy-resources/.*\\)\\]\\]"))
(when result-string
(with-temp-buffer
(insert result-string)
(goto-char (point-min))
(while (re-search-forward fregex nil t)
(push (match-string 1) files)))
(mapc (lambda (f)
(when (f-exists? f)
(f-delete f)))
files))))
;; [2019-02-24 Sun] this line removes results in dependent blocks which isn't what we want.
;; (org-babel-remove-result nil t)
;; scimax feature to restart
(when (assoc :restart params)
(let ((session (cdr (assoc :session (third (or (org-babel-get-src-block-info)
(org-babel-lob-get-info)))))))
(ob-ipython-kill-kernel
(cdr (assoc session
(ob-ipython--get-kernel-processes))))
(cl-loop for buf in (list (format "*Python:%s*" session)
(format "*ob-ipython-kernel-%s*" session))
do
(when (get-buffer buf)
(kill-buffer buf)))))
;; I think this returns the results that get inserted by
;; `org-babel-execute-src-block'. If there is an exec-dir, we wrap this block
;; to temporarily change to that directory.
(let* ((exec-dir (cdr (assoc :dir params)))
(exec-body (concat
(when exec-dir
(concat "from os import chdir as __ob_ipy_chdir; "
"from os import getcwd as __ob_ipy_getcwd; "
"__ob_ipy_cwd = __ob_ipy_getcwd(); "
" __ob_ipy_chdir(\""
exec-dir
"\")\n"))
body
(when exec-dir
"\n__ob_ipy_chdir(__ob_ipy_cwd)"))))
;; Check if we are debugging
(if (string-match "^%pdb" exec-body)
(progn
(pop-to-buffer (org-babel-initiate-session))
(comint-send-string (get-buffer-process (current-buffer)) body)
(comint-send-input))
;; not debugging
(if (assoc :async params)
(ob-ipython--execute-async exec-body params)
(ob-ipython--execute-sync exec-body params)))))
;; ** Fine tune the output of blocks
;; It was necessary to redefine these to get selective outputs via :display
(defun ob-ipython--execute-async (body params)
"Execute asynchronously."
(let* ((file (cdr (assoc :ipyfile params)))
(session (cdr (assoc :session params)))
(result-type (cdr (assoc :result-type params)))
(result-params (cdr (assoc :result-params params)))
(sentinel (ipython--async-gen-sentinel))
;; I added this. It is like the command in jupyter, but unfortunately
;; similar to :display in the results from jupyter. This is to specify
;; what you want to see.
(display-params (cdr (assoc :display params)))
(display (when display-params (mapcar 'intern-soft
(s-split " " display-params t)))))
(ob-ipython--create-kernel (ob-ipython--normalize-session session)
(cdr (assoc :kernel params)))
(ob-ipython--execute-request-async
(org-babel-expand-body:generic (encode-coding-string body 'utf-8)
params (org-babel-variable-assignments:python params))
(ob-ipython--normalize-session session)
`(lambda (ret sentinel buffer file result-type)
(when ,display-params
(setf (cdr (assoc :display (assoc :result ret)))
(-filter (lambda (el) (memq (car el) ',display))
(cdr (assoc :display (assoc :result ret)))))
(setf (cdr (assoc :value (assoc :result ret)))
(-filter (lambda (el) (memq (car el) ',display))
(cdr (assoc :value (assoc :result ret))))))
(save-window-excursion
(save-excursion
(save-restriction
(with-current-buffer buffer
(goto-char (point-min))
(re-search-forward sentinel)
(re-search-backward "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)")
(org-babel-remove-result)
(org-babel-insert-result
(ob-ipython--process-response ret file result-type)
',result-params)
(org-redisplay-inline-images))))))
(list sentinel (current-buffer) file result-type))
(format "%s - %s <output> <interrupt>" (length ob-ipython--async-queue) sentinel)))
(defun ob-ipython--execute-sync (body params)
"Execute BODY with PARAMS synchronously."
(let* ((file (cdr (assoc :ipyfile params)))
(session (cdr (assoc :session params)))
(result-params (cdr (assoc :result-params params)))
(result-type (cdr (assoc :result-type params)))
;; I added this. It is like the command in jupyter, but unfortunately
;; similar to :display in the results from jupyter. This is to specify
;; what you want to see.
(display-params (cdr (assoc :display params)))
(display (when display-params (mapcar 'intern-soft
(s-split " " display-params t)))))
(ob-ipython--create-kernel (ob-ipython--normalize-session session)
(cdr (assoc :kernel params)))
(-when-let (ret (ob-ipython--eval
(ob-ipython--execute-request
(org-babel-expand-body:generic
(encode-coding-string body 'utf-8)
params (org-babel-variable-assignments:python params))
(ob-ipython--normalize-session session))))
;; Now I want to filter out things not in the display we want. Default is everything.
(when display-params
(setf (cdr (assoc :display (assoc :result ret)))
(-filter (lambda (el) (memq (car el) display))
(cdr (assoc :display (assoc :result ret)))))
(setf (cdr (assoc :value (assoc :result ret)))
(-filter (lambda (el) (memq (car el) display))
(cdr (assoc :value (assoc :result ret))))))
(let ((*ob-ipython-output-results-prefix* (if (-contains? result-params "raw") "" ": ")))
(ob-ipython--process-response ret file result-type)))))
(defun ob-ipython-execution-count-suppress (N)
"Function that does not display the execution count."
"")
(defun ob-ipython-execution-count-output (N)
"Return a string for the execution count in the output."
(format "# Out [%d]: \n" N))
(defun ob-ipython-clear-execution-count-overlays ()
"Clear the execution count overlays."
(interactive)
(ov-clear 'ob-ipython-execution-count)
(set-window-margins (get-buffer-window) 0))
(defun ob-ipython-execution-count-overlay (N)
"Put the execution count in an overlay in the left margin.
The overlays are not persistent, and are not saved."
(set-window-margins (get-buffer-window) ob-ipython-count-overlay-width)
(let ((display-string (format "Out [%d]: " N))
ov)
(save-excursion