forked from gcv/julia-snail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjulia-snail.el
1571 lines (1411 loc) · 67.8 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") (vterm "0.0.1"))
;; Version: 1.1.5
;; 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 'json)
(require 'pulse)
(require 'rx)
(require 's)
(require 'seq)
(require 'spinner)
(require 'subr-x)
(require 'thingatpt)
(require 'vterm)
(require 'xref)
;;; --- 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-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-company-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-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" "Manifest.toml" "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))
;;; --- 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-local julia-snail--repl-go-back-target 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)
;;; --- Snail protocol request tracking data structure
(cl-defstruct julia-snail--request-tracker
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)
;;; --- 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)
"Highlight the region outlined by START and END for TIMEOUT period."
(pulse-momentary-highlight-region start end 'highlight))
(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)))
(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 (symbol-file '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 %s -L %s" julia-snail-executable extra-args julia-snail--server-file))
;; remote REPL
((string-equal "ssh" 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)))))
(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--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 "")))))
;;; --- 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
2000)))
(unless (buffer-live-p repl-buf)
(user-error "The vterm 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"
(let
((go-back-file (buffer-file-name julia-snail--repl-go-back-target)))
(if go-back-file (file-remote-p go-back-file '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)
;; connect to the server
(let ((netstream (let ((attempt 0)
(max-attempts 5)
(stream nil))
(while (and (< attempt max-attempts) (null stream))
(cl-incf attempt)
(message "Snail connecting to Julia process, attempt %d/5..." attempt)
(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
)
;;; --- 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))
(with-current-buffer repl-buf
(vterm-send-string str)
(when send-return (vterm-send-return)))
(unless async
;; 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
(funcall callback-success request-info data)))
:callback-failure (lambda (request-info)
(unless async
(setq res :nothing))
(when callback-failure
(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
;; response. This means they can either (1) succeed, (2) timeout, or (3)
;; error out. Because errors occur in the process filter function and
;; therefore outside the scope of a potential condition-case, they must be
;; processed with a non-local transfer of control (throw and catch).
(let ((wait-result
(catch 'julia-snail--server-filter-error
(julia-snail--wait-while (eq res-sentinel res) async-poll-interval async-poll-maximum))))
;; wait-result can be t if poll succeeded, nil if it timed out, and an
;; error if something blew up. Note that an explicit check for t is
;; necessary here because wait-result can be truthy but nevertheless an
;; error. This happens if an error value is caught in the `catch'.
(if (eq t wait-result)
res
(let ((error-msg (if (null wait-result)
"Snail command timed out"
(format "Snail error: %s" wait-result))))
(when callback-failure
(funcall callback-failure))
(with-current-buffer originating-buf
(spinner-stop))
(error error-msg)))))))
(cl-defun julia-snail--send-to-server-via-tmp-file
(module
str
filename
line-num
&key
(repl-buf (get-buffer julia-snail-repl-buffer))
callback-success
callback-failure)
"Send STR to server by first writing it to a tmpfile, calling
Julia include on the tmpfile, and then deleting the file. The
code in the tmpfile will be parsed in Julia as if it were
actually located in FILENAME starting at LINE-NUM and will be
evaluated in the context of MODULE."
(declare (indent defun))
(let* ((text (concat "begin\n" (s-trim str) "\nend\n"))
(module-ns (julia-snail--construct-module-path module))
(tmpfile (make-temp-file
(expand-file-name "julia-tmp" ; NOT julia-snail--efn
(or small-temporary-file-directory
(temporary-file-directory)))))
(tmpfile-local-remote (file-remote-p tmpfile 'localname)))
(progn
(with-temp-file tmpfile
(insert text))
(let ((reqid (julia-snail--send-to-server
:Main
(format "Main.JuliaSnail.eval_tmpfile(\"%s\", %s, \"%s\", %s)"
(or tmpfile-local-remote tmpfile)
module-ns
filename
line-num)
:repl-buf repl-buf
;; TODO: Only async via-tmp-file evaluation is currently
;; supported because we rely on getting the reqid back from
;; julia-snail--send-to-server, and that only happens with
;; (async t). This may or may not be worth fixing in the
;; future.
:async t
:callback-success callback-success
:callback-failure callback-failure)))
(puthash reqid
(make-julia-snail--request-tracker
:repl-buf repl-buf
:originating-buf (current-buffer)
:callback-success callback-success
:callback-failure callback-failure
:tmpfile tmpfile
:tmpfile-local-remote tmpfile-local-remote)
julia-snail--requests)
reqid))))
(defun julia-snail--server-response-filter (proc str)
"Snail process filter for PROC given input STR; used as argument to `set-process-filter'."
(when (buffer-live-p (process-buffer proc))
(with-current-buffer (process-buffer proc)
;; insert at the end unconditionally
(goto-char (point-max))
(insert str)
(set-marker (process-mark proc) (point))
;; Need to read and eval the value sent in by the process (str). But it
;; may have been chunked. Assume that a successful read signals the end of
;; input, but a failed read needs to be concatenated to other upcoming
;; reads. Track them in a table hashed by the proc.
(let ((candidate (s-concat (gethash proc julia-snail--proc-responses) str)))
(condition-case err
(let ((read-str (read candidate)))
;; read succeeds, so clean up and return its eval value
(remhash proc julia-snail--proc-responses)
;; scary
(eval read-str))
;; read failed due to end-of-file: this means more data is incoming; continue
(end-of-file
(puthash proc candidate julia-snail--proc-responses))
;; If an unexpected error occurs at this point, it will have no normal
;; condition-case context. Unfortunately, this leaves non-local
;; transfer of control as the only way to notify the rest of the
;; program that something went haywire.
(error
(throw 'julia-snail--server-filter-error err)))))))
;;; --- Snail server response handling functions
(defun julia-snail--response-base (reqid)
"Snail response handler for REQID, base function."
(let ((request-info (gethash reqid julia-snail--requests)))
(when request-info
;; tmpfile
(when-let (tmpfile (julia-snail--request-tracker-tmpfile request-info))
(delete-file tmpfile))
;; stop spinner
(with-current-buffer (julia-snail--request-tracker-originating-buf request-info)
(spinner-stop))
;; remove request ID from requests hash
(remhash reqid julia-snail--requests))))
(defun julia-snail--response-success (reqid result-data)
"Snail success response handler for REQID given RESULT-DATA."
(let* ((request-info (gethash reqid julia-snail--requests))
(callback-success (julia-snail--request-tracker-callback-success request-info)))
(when callback-success
(funcall callback-success request-info result-data)))
(julia-snail--response-base reqid))
(defun julia-snail--response-failure (reqid error-message error-stack)
"Snail failure response handler for REQID, display ERROR-MESSAGE and ERROR-STACK."
(if (not julia-snail-show-error-window)
(message error-message)
(let* ((request-info (gethash reqid julia-snail--requests))
(repl-buf (julia-snail--request-tracker-repl-buf request-info))
(process-buf (get-buffer (julia-snail--process-buffer-name repl-buf)))
(error-buffer (julia-snail--message-buffer
repl-buf
"error"
(format "%s\n\n%s" error-message (s-join "\n" error-stack))))
(callback-failure (julia-snail--request-tracker-callback-failure request-info)))
(when (julia-snail--request-tracker-display-error-buffer-on-failure? request-info)
(julia-snail--setup-compilation-mode error-buffer (gethash process-buf julia-snail--cache-proc-basedir))
(pop-to-buffer error-buffer))
(when callback-failure
(funcall callback-failure request-info))))
(julia-snail--response-base reqid))
;;; --- CST parser interface
(defun julia-snail--cst-module-at (buf pt)
(let* ((byteloc (position-bytes pt))
(encoded (julia-snail--encode-base64 buf))
(res (julia-snail--send-to-server
:Main
(format "JuliaSnail.CST.moduleat(\"%s\", %d)" encoded byteloc)
:async nil)))
(if (eq res :nothing)
nil
res)))
(defun julia-snail--cst-block-at (buf pt)
(let* ((byteloc (position-bytes pt))
(encoded (julia-snail--encode-base64 buf))
(res (julia-snail--send-to-server
:Main
(format "JuliaSnail.CST.blockat(\"%s\", %d)" encoded byteloc)
:async nil)))
(if (eq res :nothing)
nil
res)))
(defun julia-snail--cst-includes (buf)
(let* ((encoded (julia-snail--encode-base64 buf))
(pwd (file-name-directory (julia-snail--efn (buffer-file-name buf))))
(res (julia-snail--send-to-server
:Main
(format "JuliaSnail.CST.includesin(\"%s\", \"%s\")" encoded pwd)
:async nil))
(includes (make-hash-table :test #'equal)))
(unless (eq res :nothing)
(cl-loop for (file modules) in (-partition 2 res) do
(puthash file modules includes)))
;; TODO: Maybe there's a situation in which returning :error is appropriate?
includes))
;;; --- Julia module tracking implementation
(defun julia-snail--module-merge-includes (current-filename includes)
"Update file module cache using INCLUDES tree parsed from CURRENT-FILENAME."
(let* ((process-buf (get-buffer (julia-snail--process-buffer-name julia-snail-repl-buffer)))
(proc-includes (or (gethash process-buf
julia-snail--cache-proc-implicit-file-module)
(puthash process-buf (make-hash-table :test #'equal)
julia-snail--cache-proc-implicit-file-module)))
(current-file-module (gethash (julia-snail--efn current-filename) proc-includes)))
;; merge includes with the proc-includes table
(cl-loop for included-file being the hash-keys of includes using (hash-values included-file-modules) do
(puthash included-file
(if current-file-module
(append current-file-module included-file-modules)
included-file-modules)
proc-includes))
;; done
proc-includes))
(defun julia-snail--module-for-file (file)
"Retrieve the module for FILE from `julia-snail--cache-proc-implicit-file-module' table."
(let* ((filename (julia-snail--efn file))
(process-buf (get-buffer (julia-snail--process-buffer-name julia-snail-repl-buffer)))
(proc-includes (gethash process-buf julia-snail--cache-proc-implicit-file-module
(make-hash-table :test #'equal)))
(parent-modules (gethash filename proc-includes (list))))
parent-modules))
(defun julia-snail--module-at-point (&optional partial-module)
"Return the current Julia module at point as an Elisp list, including PARTIAL-MODULE if given."
(let ((partial-module (or partial-module
(julia-snail--cst-module-at (current-buffer) (point))))
(module-for-file (julia-snail--module-for-file (buffer-file-name (buffer-base-buffer)))))
(or (if module-for-file
(append module-for-file partial-module)
partial-module)
'("Main"))))
;;; --- xref implementation
(defun julia-snail-xref-backend ()
"Emacs xref API."
'xref-julia-snail)
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql xref-julia-snail)))
"Emacs xref API."
(julia-snail--identifier-at-point))
(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql xref-julia-snail)))
"Emacs xref API."
(let* ((module (julia-snail--module-at-point))
(ns (s-join "." module)))
(julia-snail--send-to-server
module
(format "Main.JuliaSnail.lsnames(%s, all=true, imported=true, include_modules=false, recursive=true)" ns)
:async nil)))
(defun julia-snail--make-xrefs-helper (response)
"Emacs xref API helper for RESPONSE."
(if (or (null response) (eq :nothing response))
nil