-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathjulia-snail.el
2068 lines (1863 loc) · 90.3 KB
/
julia-snail.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
;;; julia-snail.el --- Julia Snail -*- lexical-binding: t -*-
;; URL: https://github.com/gcv/julia-snail
;; Package-Requires: ((emacs "26.2") (dash "2.16.0") (julia-mode "0.3") (s "1.12.0") (spinner "1.7.3") (popup "0.5.9"))
;; Version: 1.3.2
;; Created: 2019-10-27
;; 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 <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides an interactive development environment for Julia
;; (https://julialang.org/), similar to SLIME for Common Lisp and CIDER for
;; Clojure. Refer to the README.md file for documentation.
;;; Code:
;;; --- requirements
(require 'cl-lib)
(require 'dash)
(require 'easymenu)
(require 'json)
(require 'popup)
(require 'pulse)
(require 'rx)
(require 's)
(require 'seq)
(require 'spinner)
(require 'subr-x)
(require 'thingatpt)
(require 'xref)
;; XXX: One of vterm or eat must be manually installed before Snail starts.
;; Picking one or the other involves tradeoffs best left to the user, and
;; therefore neither is added to the Package-Requires header. Briefly, vterm
;; supports older versions of Emacs (down to 26) but has more complicated module
;; compilation needs. Eat is a simpler dependency, but requires Emacs 28. The
;; two emulate terminals differently, and so one may be preferable to the other
;; for other reasons.
(when (not (or (locate-library "vterm")
(locate-library "eat")))
(user-error "Neither vterm nor eat dependencies detected; please install one or the other"))
(when (locate-library "vterm")
(require 'vterm))
(declare-function vterm-end-of-line "vterm.el")
(declare-function vterm-mode "vterm.el")
(declare-function vterm-send-key "vterm.el")
(declare-function vterm-send-return "vterm.el")
(declare-function vterm-send-string "vterm.el")
(defvar vterm-shell)
(when (locate-library "eat")
(require 'eat))
(declare-function eat-term-send-string "eat.el")
(declare-function eat-self-input "eat.el")
(defvar eat-terminal)
;;; --- customizations
(defgroup julia-snail nil
"Customization options for Julia Snail mode."
:group 'external)
(defcustom julia-snail-executable "julia"
"Julia executable to run as a Snail server."
:tag "Julia executable"
:group 'julia-snail
:safe 'stringp
:type 'string)
(make-variable-buffer-local 'julia-snail-executable)
(defcustom julia-snail-extra-args nil
"Extra arguments to pass to the Julia binary, e.g. '--sysimage /path/to/image'."
:tag "Extra arguments (string or list of strings)"
:group 'julia-snail
:safe (lambda (obj) (or (null obj) (stringp obj) (listp obj)))
:type '(choice (const :tag "None" nil)
(string :tag "Single string")
(repeat :tag "List of strings" string)))
(make-variable-buffer-local 'julia-snail-extra-args)
(defcustom julia-snail-port 10011
"Default Snail server port for Emacs to connect to."
:tag "Snail server port (local)"
:group 'julia-snail
:safe 'integerp
:type 'integer)
(make-variable-buffer-local 'julia-snail-port)
(defcustom julia-snail-remote-port nil
"Default Snail server port when using a remote REPL. Do not set UNLESS using a remote REPL!"
:tag "Snail server port (remote); do not set unless using remote REPL"
:group 'julia-snail
:safe (lambda (obj) (or (null obj) (integerp obj)))
:type '(choice (const :tag "Same as local" nil)
(integer)))
(make-variable-buffer-local 'julia-snail-remote-port)
(defcustom julia-snail-repl-buffer "*julia*"
"Default buffer to use for Julia REPL interaction."
:tag "Julia REPL buffer"
:group 'julia-snail
:safe 'stringp
:type 'string)
(make-variable-buffer-local 'julia-snail-repl-buffer)
(defcustom julia-snail-terminal-type
(if (locate-library "vterm") :vterm :eat) ; default to :vterm for historical compatibility
"Which Emacs terminal emulator to use for the Julia REPL."
:tag "Terminal type"
:group 'julia-snail
:options '(:eat :vterm)
:safe (lambda (v) (memq v '(:eat :vterm)))
:type '(choice (const :tag "Eat" :eat)
(const :tag "vterm" :vterm)))
;;(make-variable-buffer-local 'julia-snail-terminal-type) ; XXX: Let's not make this a buffer-local switch. Too messy.
(defcustom julia-snail-show-error-window t
"When t: show compilation errors in separate window. When nil: display errors in the minibuffer."
:tag "Show compilation errors in separate window"
:group 'julia-snail
:type 'boolean)
(defcustom julia-snail-async-timeout 20000
"When performing asynchronous Snail operations, wait this many milliseconds before timing out."
:tag "Timeout for asynchronous Snail operations"
:group 'julia-snail
:safe 'integerp
:type 'integer)
(defcustom julia-snail-multimedia-enable nil
"When t: enable Emacs integration with the Julia multimedia system."
:tag "Enable Julia multimedia integration"
:group 'julia-snail
:safe 'booleanp
:type 'boolean)
(make-variable-buffer-local 'julia-snail-multimedia-enable)
(defcustom julia-snail-multimedia-buffer-autoswitch nil
"If true, when an image is displayed inside Emacs, the
multimedia buffer gets the focus (e.g., for zooming and panning).
If nil, the image window is displayed but focus remains on the
REPL buffer."
:tag "Automatically switch to multimedia (plot) content buffer"
:group 'julia-snail
:type 'boolean)
(defcustom julia-snail-multimedia-buffer-style :single-reuse
"Controls multimedia buffer behavior. When
:single-reuse (default), reuse the same buffer to show every
image; this erases previous images. When :single-new, open a new
buffer for every image. When :multi, insert images one after
another."
:tag "Control multimedia buffer behavior"
:group 'julia-snail
:options '(:single-reuse :single-new :multi)
:safe (lambda (v) (memq v '(:single-reuse :single-new :multi)))
:type '(choice (const :tag "Reuse buffer and replace image" :single-reuse)
(const :tag "New buffer for each image" :single-new)
(const :tag "Append images to buffer" :multi)))
(make-variable-buffer-local 'julia-snail-multimedia-buffer-style)
(defcustom julia-snail-completions-doc-enable t
"If company-mode is installed, this flag determines if its documentation integration should be enabled."
:tag "Control company-mode documentation integration"
:group 'julia-snail
:safe 'booleanp
:type 'boolean)
(defcustom julia-snail-use-emoji-mode-lighter t
"If true, try to use a snail emoji in the modeline lighter instead of text."
:tag "Control use of emoji in modeline lighter"
:group 'julia-snail
:safe 'booleanp
:type 'boolean)
(defcustom julia-snail-repl-display-eval-results nil
"If true, show the results of evaluating code sent from Emacs in the Julia REPL."
:tag "Control display of eval results in Julia REPL"
:group 'julia-snail
:safe 'booleanp
:type 'boolean)
(defcustom julia-snail-popup-display-eval-results :command
"Control display of code evaluation results in source buffers."
:tag "Control display of code evaluation results in source buffers"
:group 'julia-snail
:safe (lambda (v) (memq v '(:command :change nil)))
:type '(choice (const :tag "Until next command" :command)
(const :tag "Until next buffer change" :change)
(const :tag "Off" nil)))
(defcustom julia-snail-popup-display-face nil
"Face used to display popups. If nil, try to make popups look reasonable."
:group 'julia-snail
:type 'face)
(defcustom julia-snail-imenu-style :module-tree
"Control how imenu should be structured.
nil means disable Snail-specific imenu integration (fall back on julia-mode implementation).
:flat means entries are prefixed by Julia module, e.g. 'MyModule.myfunction1()'
:module-tree means entries use Julia modules to make subtrees, so 'myfunction1()' becomes an entry under 'MyModule'. This is useful with something like the imenu-list package."
:tag "Control imenu integration"
:group 'julia-snail
:safe (lambda (v) (memq v '(:flat :module-tree nil)))
:set (lambda (symbol value)
(set-default symbol value)
;; invalidate the cache in all buffers
(cl-loop for buf in (buffer-list) do
(with-current-buffer buf
(defvar julia-snail--imenu-cache)
(setq julia-snail--imenu-cache nil))))
:type '(choice (const :tag "Flat" :flat)
(const :tag "Module-based tree structure" :module-tree)
(const :tag "Use julia-mode" nil)))
(defcustom julia-snail-extensions (list)
"A list of enabled Snail extensions."
:tag "Enabled Snail extensions"
:group 'julia-snail
:safe (lambda (obj)
(and (listp obj)
(seq-every-p #'symbolp obj)))
:type '(repeat :tag "Extension" symbol))
(make-variable-buffer-local 'julia-snail-extensions)
;;; --- constants
(defconst julia-snail--julia-files
;; a slightly specialized directory walker to collect the correct file and directory list:
(cl-labels ((list-extension-files (&optional (path "extensions"))
(let* ((result nil)
(entries (cl-remove-if
(lambda (entry)
(or (string-match-p "^\\." (file-name-nondirectory entry))
(and (file-regular-p (concat (file-name-as-directory path) entry))
(not (or (string-equal "jl" (downcase (or (file-name-extension entry) "")))
(string-equal "toml" (downcase (or (file-name-extension entry) ""))))))))
(directory-files path)))
(qualified-entries (if (string-equal "." path)
entries
(mapcar (lambda (entry)
(concat (file-name-as-directory path) entry))
entries))))
(cl-loop for entry in qualified-entries do
(if (file-regular-p entry)
(setq result (cons entry result))
(when (file-directory-p entry)
(setq result (cons entry result))
(setq result (append result (list-extension-files entry))))))
result)))
;; actually put together the list
(append
(list "JuliaSnail.jl" "Project.toml" "extensions")
(let ((default-directory (file-name-directory (or load-file-name (buffer-file-name)))))
(list-extension-files)))))
(defconst julia-snail--julia-files-local
(mapcar (lambda (f)
(concat (file-name-directory (or load-file-name (buffer-file-name))) f))
julia-snail--julia-files))
(defconst julia-snail--server-file
(-find (lambda (f)
(string-equal "JuliaSnail.jl" (file-name-nondirectory f)))
julia-snail--julia-files-local))
;;; --- supporting data structures
(cl-defstruct julia-snail--request-tracker
"Snail protocol request tracking data structure."
repl-buf
originating-buf
(callback-success (lambda (&optional _data) (message "Snail command succeeded")))
(callback-failure (lambda () (message "Snail command failed")))
(display-error-buffer-on-failure? t)
tmpfile
tmpfile-local-remote)
(cl-defstruct julia-snail--imenu-cache-entry
timestamp
tick
value)
;;; --- variables
(defvar julia-snail-debug nil
"When t, show more runtime information.")
(defvar-local julia-snail--process nil)
;;; TODO: Maybe this should hash by proc+reqid rather than just reqid?
(defvar julia-snail--requests
(make-hash-table :test #'equal))
(defvar julia-snail--proc-responses
(make-hash-table :test #'equal))
(defvar julia-snail--cache-proc-implicit-file-module
(make-hash-table :test #'equal))
(defvar julia-snail--cache-proc-basedir
(make-hash-table :test #'equal))
(defvar julia-snail--imenu-fallback-index-function nil)
(defvar-local julia-snail--repl-go-back-target nil)
(defvar-local julia-snail--popups (list))
(defvar-local julia-snail--imenu-cache nil)
(defvar julia-snail--compilation-regexp-alist
'(;; matches "while loading /tmp/Foo.jl, in expression starting on line 2"
(julia-load-error . ("while loading \\([^ ><()\t\n,'\";:]+\\), in expression starting on line \\([0-9]+\\)" 1 2))
;; matches "around /tmp/Foo.jl:2", also starting with "at" or "Revise"
(julia-loc . ("\\(around\\|at\\|Revise\\) \\([^ ><()\t\n,'\";:]+\\):\\([0-9]+\\)" 2 3))
;; matches "omitting file /tmp/Foo.jl due to parsing error near line 2", from Revise.parse_source!
(julia-warn-revise . ("omitting file \\([^ ><()\t\n,'\";:]+\\) due to parsing error near line \\([0-9]+\\)" 1 2))
)
"Specifications for highlighting error locations.
Uses function `compilation-shell-minor-mode'.")
;;; --- pre-declarations
(defvar julia-snail-mode)
(defvar julia-snail-repl-mode)
;;; --- supporting functions
(defun julia-snail--copy-buffer-local-vars (from-buf)
"Copy Snail-related buffer-local variables from FROM-BUF to the current buffer."
(dolist (blv (buffer-local-variables from-buf))
(let* ((var (car blv))
(var-name (symbol-name var))
(val (cdr blv)))
(when (and (string-prefix-p "julia-snail-" var-name)
(not (string-suffix-p "-mode" var-name)))
(set var val)))))
(defun julia-snail--process-buffer-name (repl-buf)
"Return the process buffer name for REPL-BUF."
(let ((real-buf (get-buffer repl-buf)))
(unless real-buf
(error "No REPL buffer found"))
(format "%s process" (buffer-name (get-buffer real-buf)))))
(cl-defun julia-snail--message-buffer (repl-buf name message &key (markdown nil))
"Return a buffer named NAME linked to REPL-BUF containing MESSAGE."
(let ((real-buf (get-buffer repl-buf)))
(unless real-buf
(error "No REPL buffer found"))
(let* ((msg-buf-name (format "%s %s" (buffer-name (get-buffer real-buf)) name))
(msg-buf (get-buffer-create msg-buf-name)))
(with-current-buffer msg-buf
(read-only-mode -1)
(erase-buffer)
(insert message)
(goto-char (point-min))
(when (and markdown (fboundp 'markdown-mode))
(defvar markdown-hide-markup)
(declare-function markdown-mode "markdown-mode.el")
(declare-function markdown-view-mode "markdown-mode.el")
(let ((markdown-hide-markup t))
;; older versions of markdown-mode do not have markdown-view-mode
(if (fboundp 'markdown-view-mode)
(markdown-view-mode)
(markdown-mode))))
(read-only-mode 1)
(julia-snail-message-buffer-mode 1))
msg-buf)))
;; set error buffer to compilation mode, so that one may directly jump to the relevant files
;; adapted from julia-repl by Tamas Papp
(defun julia-snail--setup-compilation-mode (message-buffer basedir)
"Setup compilation mode for the the current buffer in MESSAGE-BUFFER.
BASEDIR is used for resolving relative paths."
(with-current-buffer message-buffer
(setq-local compilation-error-regexp-alist-alist
julia-snail--compilation-regexp-alist)
(setq-local compilation-error-regexp-alist
(mapcar #'car compilation-error-regexp-alist-alist))
(compilation-mode)
(when basedir
(setq-local compilation-search-path (list basedir)))))
(defun julia-snail--flash-region (start end &optional timeout)
"Highlight the region outlined by START and END for TIMEOUT period."
(if (display-graphic-p)
;; this (sometimes?) does not seem to work in terminal Emacs (?!); the
;; overlay does not go away like it does in GUI Emacs
(pulse-momentary-highlight-region start end 'highlight)
;; borrowed from SLIME:
(let ((overlay (make-overlay start end)))
(overlay-put overlay 'face 'highlight)
(run-with-timer (or timeout 0.2) nil 'delete-overlay overlay))))
(defun julia-snail--construct-module-path (module)
"Return a Julia array representing the module path of MODULE as Julia symbols.
MODULE can be:
- nil, which returns [:Main]
- an Elisp keyword, which returns [<keyword>], including the
leading colon in the keyword
- an Elisp list, which can contain either keywords or strings,
and which is converted to a Julia array literal with the
entries of the input list converted to Julia keywords"
(cond ((null module) "[:Main]")
((keywordp module) (format "[%s]" module))
((listp module) (format
"[%s]"
(s-join " " (-map (lambda (s)
(if (keywordp s)
(format "%s" s)
(format ":%s" s)))
module))))
(t (error "Malformed module specification"))))
(defmacro julia-snail--with-syntax-table (&rest body)
"Evaluate BODY with a Snail-specific syntax table."
(declare (indent defun))
`(let ((stab (copy-syntax-table)))
(with-syntax-table stab
(modify-syntax-entry ?. "_")
(modify-syntax-entry ?@ "_")
(modify-syntax-entry ?= " ")
(modify-syntax-entry ?$ " ")
,@body)))
(defun julia-snail--bslash-before-p (pos)
(when-let (c (char-before pos))
(char-equal c ?\\)))
(defun julia-snail--identifier-at-point ()
"Return identifier at point using Snail-specific syntax table."
(julia-snail--with-syntax-table
(let ((identifier (thing-at-point 'symbol t))
(start (car (bounds-of-thing-at-point 'symbol))))
(if (julia-snail--bslash-before-p start)
(concat "\\" identifier)
identifier))))
(defun julia-snail--identifier-at-point-bounds ()
"Return the bounds of the identifier at point using Snail-specific syntax table."
(julia-snail--with-syntax-table
(let ((bounds (bounds-of-thing-at-point 'symbol)))
(if (julia-snail--bslash-before-p (car bounds))
`(,(- (car bounds) 1) . ,(cdr bounds))
bounds))))
(defmacro julia-snail--wait-while (condition increment maximum)
"Synchronously wait as long as CONDITION evaluates to true.
INCREMENT: polling frequency, ms.
MAXIMUM: max timeout, ms.
Returns nil if the poll timed out, t otherwise."
(let ((sleep-total (gensym))
(incr (gensym))
(max (gensym)))
`(let ((,sleep-total 0.0)
;; convert arguments from milliseconds to seconds for sit-for
(,incr (/ ,increment 1000.0))
(,max (/ ,maximum 1000.0)))
(while (and (< ,sleep-total ,max) ,condition)
;; XXX: This MUST be sleep-for, not sit-for. sit-for is interrupted by
;; input, which breaks the loop on input, which will inadvertently kill
;; the wait.
(redisplay)
(sleep-for ,incr)
(setf ,sleep-total (+ ,sleep-total ,incr)))
;; return value: t if wait returned early, nil if it timed out
(< ,sleep-total ,max))))
(defun julia-snail--capture-basedir (buf)
(julia-snail--send-to-server
:Main
"normpath(joinpath(VERSION <= v\"0.7-\" ? JULIA_HOME : Sys.BINDIR, Base.DATAROOTDIR, \"julia\", \"base\"))"
:repl-buf buf
:async nil))
(defun julia-snail-test-file-path (file)
"Test suite accessory: Return path to FILE in the test area."
;; XXX: Obnoxious Elisp path construction.
(let ((location (file-name-directory (locate-library "julia-snail"))))
(concat
(file-name-as-directory
(concat (if load-file-name
(file-name-directory load-file-name)
(file-name-as-directory location))
(file-name-as-directory "tests")
(file-name-as-directory "files")))
file)))
(defun julia-snail-test-send-buffer-file-sync ()
"Test suite accessory: Same as julia-snail-send-buffer-file, but synchronous."
(let ((reqid (julia-snail-send-buffer-file))) ; wait for async result to return
(julia-snail--wait-while
(gethash reqid julia-snail--requests) 50 10000)))
(cl-defun julia-snail--send-helper
(block-start
block-end
&key
(allow-send-to-repl t)
(popup-block-end block-end)
(message-prefix "Evaluated"))
(let ((text (buffer-substring-no-properties block-start block-end))
(filename (julia-snail--efn (buffer-file-name (buffer-base-buffer))))
(module (if current-prefix-arg :Main (julia-snail--module-at-point)))
(line-num (line-number-at-pos block-start)))
(julia-snail--flash-region block-start block-end)
(if (and allow-send-to-repl
(consp current-prefix-arg) (> (car current-prefix-arg) 4))
;; copy directly to REPL
(let* ((_ (julia-snail--send-to-repl (s-trim text) :async nil))
(err (julia-snail--send-to-server
:Main
"Base.active_repl.waserror"
:async nil))
(popup-params (julia-snail--popup-params block-end))
(str (if (equal err :nothing)
(when julia-snail-popup-display-eval-results
(julia-snail--send-to-server
:Main
(format "JuliaSnail.PopupDisplay.format(ans, %s, %s)"
(car popup-params)
(cadr popup-params))
:async nil))
"error")))
(julia-snail--popup-display popup-block-end str :use-cleanup-kludge (eq :command julia-snail-popup-display-eval-results)))
;; evaluate through the Snail server:
(julia-snail--send-to-server-via-tmp-file
module
text
filename
line-num
:popup-display-params (julia-snail--popup-params block-end)
:callback-success (lambda (_request-info &optional data)
(julia-snail--popup-display popup-block-end (julia-snail--popup-extract-string data))
(message "%s; module %s"
message-prefix
(julia-snail--construct-module-path module)))))))
(defun julia-snail--encode-base64 (&optional buf)
(let ((s (with-current-buffer (or buf (current-buffer))
(encode-coding-string (buffer-string)
buffer-file-coding-system))))
(base64-encode-string s)))
(defun julia-snail--copy-snail-to-remote-host ()
(let* (;; checksum all relevant files as one, copy into a directory
;; keyed off the checksum if it doesn't already exist (basically cache
;; the current version of the Julia code (.jl and .toml files)
(checksum (with-temp-buffer
(cl-loop for f in julia-snail--julia-files-local do
(when (file-regular-p f)
(insert-file-contents-literally f)))
(secure-hash 'sha256 (current-buffer))))
(snail-remote-dir (concat (file-name-as-directory (temporary-file-directory))
(concat "julia-snail-" checksum "/"))))
(unless (file-exists-p snail-remote-dir)
(make-directory snail-remote-dir)
(let ((default-directory (file-name-directory (locate-library "julia-snail"))))
(cl-loop for f in julia-snail--julia-files do
(if (file-directory-p f)
(make-directory (concat snail-remote-dir f))
(copy-file f (concat snail-remote-dir (file-name-directory f)) t)))))
snail-remote-dir))
(defun julia-snail--launch-command ()
(let* ((extra-args (if (listp julia-snail-extra-args)
(mapconcat 'identity julia-snail-extra-args " ")
julia-snail-extra-args))
(remote-method (file-remote-p default-directory 'method))
(remote-user (file-remote-p default-directory 'user))
(remote-host (file-remote-p default-directory 'host))
(remote-dir-server-file (if (equal nil remote-method)
""
(concat (file-remote-p (julia-snail--copy-snail-to-remote-host) 'localname) "JuliaSnail.jl"))))
(cond
;; local REPL
((equal nil remote-method)
(format "%s -i %s -L %s" julia-snail-executable extra-args julia-snail--server-file))
;; remote REPL
((or (string-equal "ssh" remote-method)
(string-equal "sshx" remote-method)
(string-equal "scp" remote-method)
(string-equal "scpx" remote-method))
(format "ssh -t -L %1$s:localhost:%2$s %3$s %4$s %5$s -L %6$s"
julia-snail-port
(or julia-snail-remote-port julia-snail-port)
(concat
(if remote-user (concat remote-user "@") "")
remote-host)
julia-snail-executable
extra-args
remote-dir-server-file))
;; container REPL
((string-equal "docker" remote-method)
(format "docker exec -it %s %s %s -L %s"
remote-host
julia-snail-executable
extra-args
remote-dir-server-file))
;; unsupported method
(t
(user-error "Unsupported Tramp method %s" remote-method)))))
(defun julia-snail--start (source-buf)
"Underlying command for julia-snail invocation.
Supports multiple terminal implementations."
(let* ((launch-command (julia-snail--launch-command))
;; XXX: Set the error color to red to work around breakage relating to
;; some color themes and terminal combinations, see
;; https://github.com/gcv/julia-snail/issues/11
(process-environment (append '("JULIA_ERROR_COLOR=red") process-environment))
;; XXX: When a remote REPL is being started, bind the terminal buffer's
;; default-directory to the user's home because if (1) a remote REPL is
;; being started, default-directory may be remote, and (2) Tramp may
;; notice this, mess with the path, and run ssh incorrectly.
(default-directory (if (file-remote-p default-directory)
(expand-file-name "~")
default-directory)))
(let ((terml-buf
;; first, start a REPL process in a new buffer
(cond
;; vterm
((eq :vterm julia-snail-terminal-type)
(let ((vterm-shell launch-command)
(terml-buf (generate-new-buffer julia-snail-repl-buffer)))
(pop-to-buffer terml-buf)
(with-current-buffer terml-buf
(vterm-mode))
terml-buf))
;; eat
((eq :eat julia-snail-terminal-type)
(let ((terml-buf (eat launch-command t))
(repl-buffer-name julia-snail-repl-buffer))
(with-current-buffer terml-buf
(rename-buffer repl-buffer-name))
terml-buf))
;; unsupported value
(t
(user-error "unsupported value for julia-snail-terminal-type: %s" julia-snail-terminal-type)))))
;; then deal with some setup on that buffer
(with-current-buffer terml-buf
(when source-buf
(julia-snail--copy-buffer-local-vars source-buf)
(setq julia-snail--repl-go-back-target source-buf))
(julia-snail-repl-mode)))))
(defun julia-snail--efn (path &optional starting-dir)
"A variant of expand-file-name that (1) just does
expand-file-name on local files, and (2) returns the expanded
form of the remote path without any host connection string
components. Example: (julia-snail--efn \"/ssh:host:~/file.jl\")
returns \"/home/username/file.jl\"."
(let* ((expanded (expand-file-name path starting-dir))
(remote-local-path (file-remote-p expanded 'localname)))
(if remote-local-path
remote-local-path
expanded)))
(defun julia-snail--add-to-perspective (buf)
(when (and (featurep 'perspective) (bound-and-true-p persp-mode)) ; perspective-el support
(declare-function persp-add-buffer "perspective.el")
(persp-add-buffer buf))
(when (and (featurep 'persp-mode) (bound-and-true-p persp-mode)) ; persp-mode support
(declare-function persp-add-buffer "persp-mode.el")
(declare-function get-current-persp "persp-mode.el")
(persp-add-buffer buf (get-current-persp) nil)))
(defun julia-snail--spinner-print-around (fn &rest args)
"Advice for `spinner-print` to add a leading space so the spinner looks nicer in the modeline."
(let ((fn-res (apply fn args)))
(if (> (length fn-res) 0)
(concat " " fn-res)
fn-res)))
(defun julia-snail--mode-lighter (&optional extra)
(let ((snail-emoji (char-from-name "SNAIL")))
(if (and julia-snail-use-emoji-mode-lighter
snail-emoji
(char-displayable-p snail-emoji))
(format " %c%s" snail-emoji (if extra extra ""))
(format " Snail%s" (if extra extra "")))))
;;; --- color shifting utilities, adapted from mini-frame.el
(cl-defun julia-snail--color-shift (from to &key (by 27))
"Move color FROM towards TO by BY. FROM and TO are 16-bit integer values."
(let ((f (ash from -8)))
(cond
((> from to) (- f by))
((< from to) (+ f by))
(t f))))
(cl-defun julia-snail--color-shift-hex (from to &key (by 27))
"Move color FROM towards TO. FROM and TO are hex values."
(if (or (string-match-p "^unspecified" (format "%s" from))
(string-match-p "^unspecified" (format "%s" to)))
"unspecified"
(let* ((from (color-values from))
(to (color-values to)))
(format "#%02x%02x%02x"
(julia-snail--color-shift (car from) (car to) :by by)
(julia-snail--color-shift (cadr from) (cadr to) :by by)
(julia-snail--color-shift (caddr from) (caddr to) :by by)))))
;;; --- connection management functions
(defun julia-snail--clear-proc-caches (process-buf)
"Clear connection-specific internal Snail xref, completion, and module caches."
(when process-buf
(remhash process-buf julia-snail--cache-proc-implicit-file-module)
(remhash process-buf julia-snail--cache-proc-basedir)))
(defun julia-snail--repl-cleanup ()
"REPL buffer cleanup."
(let ((process-buf (get-buffer (julia-snail--process-buffer-name (current-buffer)))))
(julia-snail--clear-proc-caches process-buf)
(when process-buf
(kill-buffer process-buf)))
(setq julia-snail--process nil))
(defun julia-snail--repl-enable ()
"REPL buffer minor mode initializer."
(add-hook 'kill-buffer-hook #'julia-snail--repl-cleanup nil t)
(let ((repl-buf (current-buffer))
(process-buf (get-buffer-create (julia-snail--process-buffer-name (current-buffer)))))
(julia-snail--add-to-perspective process-buf)
(with-current-buffer process-buf
(unless julia-snail--process
(julia-snail--copy-buffer-local-vars repl-buf)
;; XXX: This is currently necessary because there does not appear to be
;; a way to pass arguments to an interactive Julia session. This does
;; not work: `julia -L JuliaSnail.jl -- $PORT`.
;; https://github.com/JuliaLang/julia/issues/10226 refers to this
;; problem and supposedly fixes it, but it does not work for me with
;; Julia 1.0.4.
;; TODO: Follow-up on https://github.com/JuliaLang/julia/issues/33752
(message "Starting Julia process and loading Snail...")
;; XXX: Wait briefly in case the Julia executable failed to launch.
(with-current-buffer repl-buf
;; XXX: This use of julia-snail--wait-while causes a mysterious
;; byte-compiler warning saying the result value of the macro is
;; unused. Indeed, this is intentional. Plenty of other places in the
;; code ignore the return value of julia-snail--wait-while, all
;; without causing the byte-compiler to complain.
(with-no-warnings
(julia-snail--wait-while
(not (string-equal "julia>" (current-word)))
100
3000)))
(unless (buffer-live-p repl-buf)
(user-error "The REPL terminal buffer is inactive; double-check julia-snail-executable path"))
;; now try to send the Snail startup command
(julia-snail--send-to-repl
(format "JuliaSnail.start(%d%s) ; # please wait, time-to-first-plot..."
(or julia-snail-remote-port julia-snail-port)
(if (string-equal "docker" (file-remote-p (buffer-file-name julia-snail--repl-go-back-target) 'method))
"; addr=\"0.0.0.0\""
""))
:repl-buf repl-buf
;; wait a while in case dependencies need to be downloaded
:polling-timeout (* 5 60 1000)
:async nil)
(let ((netstream (let ((attempt 0)
(max-attempts 15)
(stream nil))
(while (and (< attempt max-attempts) (null stream))
(cl-incf attempt)
(message "Snail connecting to Julia process, attempt %d/%d..." attempt max-attempts)
(condition-case nil
(setq stream (open-network-stream "julia-process" process-buf "localhost" julia-snail-port))
(error (when (< attempt max-attempts)
(sleep-for 0.75)))))
stream)))
(if netstream
(with-current-buffer repl-buf
;; NB: buffer-local variable!
(setq julia-snail--process netstream)
(set-process-filter julia-snail--process #'julia-snail--server-response-filter)
;; TODO: Implement a sanity check on the Julia environment. Not
;; sure how. But a failed dependency load (like CSTParser) will
;; leave Snail in a bad state.
(message "Successfully connected to Snail server in Julia REPL")
;; Query base directory, and cache
(puthash process-buf (julia-snail--capture-basedir repl-buf)
julia-snail--cache-proc-basedir))
;; something went wrong
(error "Failed to connect to Snail server"))
;; post-connection initialization:
(when netstream
(when (buffer-local-value 'julia-snail-multimedia-enable repl-buf)
(julia-snail--send-to-server
'("JuliaSnail" "Multimedia")
"display_on()"
:repl-buf repl-buf
:async nil))
;; activate extensions
(cl-loop for extname in julia-snail-extensions do
;; load the extension Elisp file (if necessary)
(julia-snail--extension-load extname)
;; run extension initialization function
(let ((init-fn (julia-snail--extension-init extname)))
(message "Loading Snail extension %s..." extname)
(when (functionp init-fn)
(funcall init-fn repl-buf))))
(when (> (length julia-snail-extensions) 0)
(message "Finished loading Snail extensions"))
;; enable REPL evaluation output
(when julia-snail-repl-display-eval-results
(julia-snail--send-to-server
'("JuliaSnail" "Conf")
"set!(:repl_display_eval_results, true)"
:repl-buf repl-buf
:async nil))
;; other initializations can go here
;; all done!
(message "Snail initialization complete. Happy hacking!")
))))))
(defun julia-snail--repl-disable ()
"REPL buffer minor mode cleanup."
(julia-snail--repl-cleanup))
(defun julia-snail--enable ()
"Source buffer minor mode initializer."
;; turn on extension minor modes
(hack-dir-local-variables-non-file-buffer) ; force .dir-locals.el to load
(cl-loop for extname in julia-snail-extensions do
;; load the extension Elisp file (if necessary)
(julia-snail--extension-load extname)
(let ((minor-mode-fn (julia-snail--extension-mode extname)))
(when (functionp minor-mode-fn)
(funcall minor-mode-fn 1))))
;; other minor mode initializations can go here
)
(defun julia-snail--disable ()
"Source buffer minor mode cleanup."
;; turn off extension minor modes
(cl-loop for extname in julia-snail-extensions do
(let ((minor-mode-fn (julia-snail--extension-mode extname)))
(when (functionp minor-mode-fn)
(funcall minor-mode-fn -1))))
;; other minor mode cleanup can go here
)
;;; --- terminal emulator compatibility wrappers
(defun julia-snail--terminal-send-string (str)
(cond
;; Eat
((eq 'eat-mode major-mode)
(eat-term-send-string eat-terminal str)
;; TODO: Remove this call when https://codeberg.org/akib/emacs-eat/issues/100 is fixed.
(when (fboundp 'eat--process-input-queue)
(declare-function eat--process-input-queue "eat.el")
(eat--process-input-queue (current-buffer))))
;; vterm
((eq 'vterm-mode major-mode)
(vterm-send-string str))
;; error and debugging
(t
(error "function called out of context; (with-current-buffer repl-buf ...) required"))))
(defun julia-snail--terminal-send-return ()
(cond
;; Eat
((eq 'eat-mode major-mode)
(eat-term-send-string eat-terminal "\n")
;; TODO: Remove this call when https://codeberg.org/akib/emacs-eat/issues/100 is fixed.
(when (fboundp 'eat--process-input-queue)
(declare-function eat--process-input-queue "eat.el")
(eat--process-input-queue (current-buffer))))
;; vterm
((eq 'vterm-mode major-mode)
(vterm-send-return))
;; error and debugging
(t
(error "function called out of context; (with-current-buffer repl-buf ...) required"))))
;;; --- Julia REPL and Snail server interaction functions
(cl-defun julia-snail--send-to-repl
(str
&key
(repl-buf (get-buffer julia-snail-repl-buffer))
(send-return t)
(async t)
(polling-interval 20)
(polling-timeout julia-snail-async-timeout))
"Insert str directly into the REPL buffer. When :async is nil,
wait for the REPL prompt to return, otherwise return immediately."
(declare (indent defun))
(unless repl-buf
(user-error "No Julia REPL buffer %s found; run julia-snail" julia-snail-repl-buffer))
(let ((pre-write-size (buffer-size repl-buf)))
(with-current-buffer repl-buf
(julia-snail--terminal-send-string str)
(when send-return (julia-snail--terminal-send-return)))
(unless async
;; wait for the buffer to accept the new input, or a race condition may
;; occur with non-async prompt check below
(julia-snail--wait-while (= pre-write-size (buffer-size repl-buf)) polling-interval polling-timeout)
;; wait for the inclusion to succeed (i.e., the prompt prints)
(julia-snail--wait-while
(with-current-buffer repl-buf
(not (string-equal "julia>" (current-word))))
polling-interval
polling-timeout))))
(cl-defun julia-snail--send-to-server
(module
str
&key
(repl-buf (get-buffer julia-snail-repl-buffer))
(async t)
(async-poll-interval 20)
(async-poll-maximum julia-snail-async-timeout)
(display-error-buffer-on-failure? t)
callback-success
callback-failure)
"Send STR to Snail server, and evaluate it in the context of MODULE.
Run callback-success and callback-failure as appropriate.
When :async is t (default), return the request id. When :async is
nil, wait for the result and return it."
(declare (indent defun))
(unless repl-buf
(user-error "No Julia REPL buffer %s found; run julia-snail" julia-snail-repl-buffer))
(let* ((process-buf (get-buffer (julia-snail--process-buffer-name repl-buf)))
(originating-buf (current-buffer))
(module-ns (julia-snail--construct-module-path module))
(reqid (format "%04x%04x" (random (expt 16 4)) (random (expt 16 4))))
(code-str (json-encode-string str))
(display-code-str (if julia-snail-debug
code-str
(s-truncate 80 code-str)))
(msg (format "(ns = %s, reqid = \"%s\", code = %s)\n"
module-ns
reqid
code-str))
(display-msg (format "(ns = %s, reqid = \"%s\", code = %s)\n"
module-ns
reqid
display-code-str))
(res-sentinel (gensym))
(res res-sentinel))
(with-current-buffer process-buf
(goto-char (point-max))
(insert display-msg))
(process-send-string process-buf msg)
(spinner-start 'progress-bar)
(puthash reqid
(make-julia-snail--request-tracker
:repl-buf repl-buf
:originating-buf originating-buf
:display-error-buffer-on-failure? display-error-buffer-on-failure?
:callback-success (lambda (request-info &optional data)
(unless async
(setq res (or data :nothing)))
(when callback-success
(with-current-buffer originating-buf
(funcall callback-success request-info data))))
:callback-failure (lambda (request-info)
(unless async
(setq res :nothing))
(when callback-failure
(with-current-buffer originating-buf
(funcall callback-failure request-info)))))
julia-snail--requests)
;; return value logic:
(if async
reqid
;; XXX: Non-async (i.e. synchronous) server requests need to poll the