-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
racket-repl.el
1860 lines (1609 loc) · 72.6 KB
/
racket-repl.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; racket-repl.el -*- lexical-binding: t; -*-
;; Copyright (c) 2013-2024 by Greg Hendershott.
;; Portions Copyright (C) 1985-1986, 1999-2013 Free Software Foundation, Inc.
;; Image portions Copyright (C) 2012 Jose Antonio Ortega Ruiz.
;; Author: Greg Hendershott
;; URL: https://github.com/greghendershott/racket-mode
;; SPDX-License-Identifier: GPL-3.0-or-later
(require 'racket-browse-url)
(require 'racket-scribble-anchor)
(require 'racket-complete)
(require 'racket-describe)
(require 'racket-doc)
(require 'racket-eldoc)
(require 'racket-custom)
(require 'racket-common)
(require 'racket-show)
(require 'racket-util)
(require 'racket-visit)
(require 'racket-cmd)
(require 'racket-back-end)
(require 'ansi-color)
(require 'compile)
(require 'easymenu)
(require 'cl-lib)
(require 'cl-macs)
(require 'rx)
(require 'xref)
(require 'semantic/symref/grep)
(require 'ring)
(declare-function racket--what-to-run-p "racket-common" (v))
;; Don't (require 'racket-debug). Mutual dependency. Instead:
(declare-function racket--debuggable-files "racket-debug" (file-to-run))
(autoload 'racket--debuggable-files "racket-debug")
;;; edit buffers <=> `racket-repl-mode' buffers
;; There are some nuances here regarding these variables being
;; buffer-local or not, and, whether the variables have any meaning in
;; certain modes, or not. We use Emacs variable semantics to handle
;; the association between `racket-mode' or `racket-hash-lang-mode'
;; edit buffers and `racket-repl-mode' buffers, for a variety of use
;; cases the user might prefer. These range from all edit buffers
;; sharing one REPL buffer (the traditional default for Racket Mode),
;; up to each edit buffers having its own REPL (as in Dr Racket), or
;; anything in between (such as one REPL per projectile project, or
;; whatever).
;;
;; Although some of these scenarios might benefit from a higher-level
;; UI, they all come down to setting the variable
;; `racket-repl-buffer-name' globally and/or locally for each edit
;; buffer -- that is the fundamental representation.
;;
;; Similarly, each `racket-repl-mode' buffer has an
;; always-buffer-local value for the variable
;; `racket--repl-session-id'. (Note that `racket-repl-buffer-name'
;; only has meaning for `racket-mode' buffers, and
;; `racket--repl-session-id' only has meaning for `racket-repl-mode'
;; buffers. Emacs variables exist for all buffers using all major
;; modes. All we can do is remember in which buffers they mean
;; something as opposed to being ignored.)
(defvar racket-repl-buffer-name nil
"The name of the `racket-repl-mode' buffer associated with `racket-mode' buffer.
Important: This variable only means something in each
`racket-mode' or `racket-hash-lang-mode' edit buffer. It has no
meaning in `racket-repl-mode' or other buffers.
When nil, all `racket-mode' edit buffers share the same REPL.
However, a buffer may `setq-local' this to some other value. See
the defcustom `racket-repl-buffer-name-function' as well as several
values for it in racket-repl-buffer-name.el.")
(defun racket--call-with-repl-buffer (thunk)
(pcase (if (eq major-mode 'racket-repl-mode)
(buffer-name)
racket-repl-buffer-name)
((and (pred stringp) name)
(pcase (get-buffer name)
((and (pred bufferp) (pred buffer-live-p) buf)
(with-current-buffer buf (funcall thunk)))))))
(defmacro with-racket-repl-buffer (&rest body)
"Execute forms in BODY with `racket-repl-mode' temporarily current buffer."
(declare (indent 0) (debug t))
`(racket--call-with-repl-buffer (lambda () ,@body)))
;;; REPL back end sessions <=> `racket-repl-mode' buffers
(defvar racket--repl-next-session-id 0)
(defvar-local racket--repl-session-id nil
"An ID for each back end REPL session.
Commands that are about a specific REPL session must supply this;
see `racket--cmd/async'.
Important: This variable only means something in each
`racket-repl-mode' buffer. It has no meaning in `racket-mode' or
other buffers. Futhermore, it is /always/ buffer-local in each
`racket-repl-mode' buffer. Instead of accessing this directly,
use the function `racket--repl-session-id', which helps select
the correct `racket-repl-mode' buffer, if any.")
(defun racket--repl-session-id ()
"Use this to get a REPL session ID.
The result might be nil if no REPL buffer exists, or if it does
but does not have a live session."
(if (eq major-mode 'racket-repl-mode)
racket--repl-session-id
(when (stringp racket-repl-buffer-name)
(let ((buffer (get-buffer racket-repl-buffer-name)))
(when buffer
(with-current-buffer racket-repl-buffer-name
racket--repl-session-id))))))
(defun racket--call-with-repl-session-id (id proc &rest args)
"Find `racket-repl-mode' buffer with `racket--repl-session-id'
`eq' to ID. Apply ARGS to PROC while that is current buffer."
;; If searching buffer-list too slow, we could maintain a hash table
;; and clean it with a kill-buffer hook.
(seq-some (lambda (buf)
(when (buffer-live-p buf)
(with-current-buffer buf
(when (and (eq major-mode 'racket-repl-mode)
(eq racket--repl-session-id id))
(apply proc args)
t))))
(buffer-list)))
(defun racket--repl-on-stop-back-end ()
(dolist (buf (buffer-list))
(with-current-buffer buf
(when (and (eq major-mode 'racket-repl-mode)
(buffer-live-p buf))
(racket--repl-insert-output 'exit "REPL session stopped")))))
(add-hook 'racket-stop-back-end-hook #'racket--repl-on-stop-back-end)
;;; Markers for run, interactions prompt, and program I/O
(defvar-local racket--repl-run-mark nil
"The point at which a run command was issued.")
;; Note: One goal here is to make read-only all of the output, as well
;; as "old" input that has already been submitted. This involves
;; paying careful attention to the read-only and rear-nonsticky
;; properties.
(defvar-local racket--repl-prompt-mark nil
"A marker for the start of the active prompt, if any.
Non-nil only when the REPL is in a prompt-read.
Marker insertion type is non-nil: text inserted there
automatically advances the marker position.
The prompt itself is read-only. `racket--repl-prompt-mark-end'
gives the position where the following read/write portion
starts.")
(defvar-local racket--repl-output-mark nil
"A marker where REPL output should be inserted, and user may input.
Plays a role similar to `process-mark' in `comint-mode', except
we have no process.
Various kinds of output get various field property values. All
output is read-only, but we arrange for the last character to be
rear-nonsticky so self-insert-command will let the user type
input. When the user types text there and presses RET, then that
is submitted as plain input -- as opposed to REPL interaction
input.
When `racket--repl-prompt-mark' marker exists, that always
/follows/ `racket--repl-output-mark'. If e.g. the user program
has a thread that continues to run after we're back at a prompt,
its output is displayed /before/ the prompt. Otherwise with no
live prompt this marker will be at `point-max'.")
(defun racket--repl-make-prompt-mark (prompt-str)
(when racket--repl-prompt-mark
(racket--repl-delete-prompt-mark t))
(let ((inhibit-read-only t))
(goto-char (point-max))
(unless (bolp)
(insert ?\n))
(let ((start (point)))
(insert (propertize (concat prompt-str " ")
'read-only t
'font-lock-face racket-repl-prompt
'field 'prompt
'racket-prompt t))
(add-text-properties (1- (point)) (point)
(list 'rear-nonsticky t))
(setq racket--repl-prompt-mark (make-marker))
(set-marker racket--repl-prompt-mark start)
;; Marker /does/ advance when text inserted there.
(set-marker-insertion-type racket--repl-prompt-mark t)
;; Ensure output marker position <= prompt marker position;
;; output always goes /before/ the last active prompt, if any.
(set-marker racket--repl-output-mark
(min (marker-position racket--repl-output-mark)
(marker-position racket--repl-prompt-mark))))))
(defun racket--repl-delete-prompt-mark (abandon-p)
(when racket--repl-prompt-mark
(let ((inhibit-read-only t))
(if abandon-p
(delete-region racket--repl-prompt-mark (point-max))
(add-text-properties (racket--repl-prompt-mark-end)
(point-max)
(list 'read-only t
'field 'input)))
(goto-char (point-max))
(set-marker racket--repl-prompt-mark nil)
(setq racket--repl-prompt-mark nil)
(set-marker racket--repl-output-mark (point-max)))))
(defun racket--repl-prompt-mark-end ()
"May return nil when there is no live prompt."
(when racket--repl-prompt-mark
(or (next-single-property-change racket--repl-prompt-mark 'racket-prompt)
(point-max))))
;;; Output
(defun racket--repl-on-output (session-id kind value)
;;;(message "%S" (list 'racket--repl-on-output session-id kind value))
(racket--call-with-repl-session-id session-id
#'racket--repl-insert-output
kind value))
(defun racket--repl-insert-output (kind value)
(let ((moving (= (point) racket--repl-output-mark))
(inhibit-read-only t))
;; Previous chunks of output may have ended with a rear-nonsticky
;; property to allow input to follow. Now that we're adding more
;; output, remove that property so there are no read/write "seams"
;; between chunks.
(let ((inhibit-modification-hooks t)) ;avoid after-change: #731
(remove-text-properties (point-min)
(point-max)
'(rear-nonsticky nil)))
(save-excursion
(goto-char racket--repl-output-mark)
(let ((pt (point)))
(cl-flet*
((faced (str face)
(propertize str 'font-lock-face face))
(insert-faced (str face &optional no-fresh-line)
(let ((str (faced str face)))
(insert (if (or no-fresh-line (bolp))
str
(concat "\n" str)))))
(insert-filtered (str face)
(insert (racket--repl-filter-output
(faced str face)))))
(pcase kind
('run
(racket--repl-delete-prompt-mark 'abandon)
(unless (equal value "")
(insert-faced (format "————— run %s —————\n" value) 'racket-repl-message)))
('prompt
(racket--repl-make-prompt-mark value))
('message
(insert-faced value 'racket-repl-message)
(unless (bolp) (newline)))
('exit
(racket--repl-delete-prompt-mark 'abandon)
(insert-faced value 'racket-repl-message)
(unless (bolp) (newline))
(setq moving t) ;leave point after, for tests
(setq racket--repl-session-id nil))
('value
(insert-faced value 'racket-repl-value t))
('value-special
(pcase value
(`(image . ,file)
(racket--repl-insert-image file))
(value
(insert-faced (format "%s" value) 'racket-repl-value t))))
('error
(pcase value
(`(,msg ,srclocs (,context-kind . ,context-names-and-locs))
(combine-after-change-calls
(insert-faced msg 'racket-repl-error-message)
(newline)
;; Heuristic: When something supplies exn-srclocs,
;; show those only. Otherwise show context if any.
;; This seems to work well for most runtime
;; exceptions, as well as for rackunit test failures
;; (where the srcloc suffices and the context esp
;; w/errortrace is useless noise).
(cond
(srclocs
(dolist (loc srclocs)
(insert " ")
(insert (racket--format-error-location loc))
(newline)))
(context-names-and-locs
(insert-faced (format "Context (%s):" context-kind)
'racket-repl-error-message)
(newline)
(dolist (v context-names-and-locs)
(pcase-let ((`(,name . ,loc) v))
(insert " ")
(insert (racket--format-error-location loc))
(insert " ")
(when name
(insert-faced name 'racket-repl-error-label t)))
(newline))))))))
('stdout
(insert-filtered value 'racket-repl-stdout))
('stderr
(insert-filtered value 'racket-repl-stderr))
(_
(insert-faced value 'racket-repl-message))))
(unless (eq kind 'prompt)
(add-text-properties pt (point)
(list
'read-only t
'field kind))
;; Make last character rear-nonsticky. Among other things,
;; means `racket--repl-output-mark' won't be read-only; and
;; user may input there (for user program reading from
;; current-input-port).
(add-text-properties (max (point-min) (1- (point))) (point)
(list 'rear-nonsticky t))
(set-marker racket--repl-output-mark (point))
;; When stdout/stderr output ends with prompt following on
;; same line, push the prompt down to its own line.
(when (and (memq kind '(stdout stderr))
racket--repl-prompt-mark
(equal (point) (marker-position racket--repl-prompt-mark)))
(insert (propertize "\n"
'read-only t
'field kind))))))
;; If we just inserted a new prompt, position after it.
(let ((win (get-buffer-window (current-buffer))))
(if (eq kind 'prompt)
(let ((pos (racket--repl-prompt-mark-end)))
(goto-char pos)
(when win (set-window-point win pos)))
;; When point was exactly at the old output marker value, move
;; point to follow it. (Otherwise user is navigating through
;; buffer, leave them alone.)
(when moving
(goto-char racket--repl-output-mark)
(when win (set-window-point win racket--repl-output-mark)))))))
(defvar racket-repl-output-filter-functions (list #'ansi-color-apply)
"List of functions to call before inserting stdout/stderr output.
Similar to `comint-preoutput-filter-functions', but limited to
stdout/stderr kinds of output.
Each function gets one argument, a string propertized by default
with a face for stdout or stderr. It should return a string to
insert instead. The functions are composed.
You can use `add-hook' to add functions to this list either
globally or locally.
If the function uses state that should be reset between runs, do
that via `racket-before-run-hook'; for example see
`racket-ansi-color-context-reset'.")
;; Because we default `racket-repl-output-filter-functions' to
;; `ansi-color-apply', we want to reset its state for a REPL before
;; every run. Although we could hard-code that, use the before-run
;; hook to set an example for users.
(defun racket-ansi-color-context-reset ()
(with-racket-repl-buffer
(setq-local ansi-color-context nil)))
(add-hook 'racket-before-run-hook #'racket-ansi-color-context-reset)
(defun racket--repl-filter-output (string)
;; Beause there is no run-hooks-xxx variant equivalent to function
;; composition, we borrow the equivalent code from comint, which
;; also handles the wrinkle of buffer-local values.
(let ((functions racket-repl-output-filter-functions))
(while (and functions string)
(if (eq (car functions) t)
(let ((functions
(default-value 'racket-repl-output-filter-functions)))
(while (and functions string)
(setq string (funcall (car functions) string))
(setq functions (cdr functions))))
(setq string (funcall (car functions) string)))
(setq functions (cdr functions))))
string)
(defun racket--repl-call-with-value-and-input-ranges (from upto proc)
"Call PROC with sub-ranges of FROM..UPTO, saying whether each
is a value or input since `racket--repl-run-mark'."
(setq upto (min upto (point-max)))
;; Everything before the last run is "stale": No.
(when (< from racket--repl-run-mark)
(funcall proc from racket--repl-run-mark nil)
(setq from racket--repl-run-mark))
(let ((prompt-end (or (racket--repl-prompt-mark-end) (point-max))))
(while (< from upto)
(cond
;; If we're at/after the end of the last, live prompt, then
;; everything remaining is input, yes, and we're done.
((<= prompt-end from)
(funcall proc from upto t)
(setq from upto))
;; Keep getting chunks at racket-output prop change boundaries,
;; until we reach the earlier of prompt-end or point-max.
(t
(let ((in (memq (get-text-property from 'field) '(value input)))
(pos (min (or (next-single-property-change from 'field)
(point-max))
prompt-end)))
(funcall proc from (min pos upto) in)
(setq from pos)))))))
;;; Submit
(defalias 'racket-repl-eval-or-newline-and-indent #'racket-repl-submit)
(defvar-local racket-repl-submit-function nil)
(defun racket-repl-submit ()
"Submit interaction or input.
When at a REPL prompt, submit as an interaction expression.
Otherwise send to current-input-port of user program."
(interactive)
(unless (racket--repl-session-id)
(user-error "no REPL session"))
(let ((prompt-end (racket--repl-prompt-mark-end)))
(if (and prompt-end (< prompt-end (point-max)))
(let* ((input (buffer-substring-no-properties prompt-end (point-max)))
(input+ret (concat input "\n")))
(when (if racket-repl-submit-function
(funcall racket-repl-submit-function input+ret)
(racket--repl-complete-sexp-p))
(racket--repl-add-to-input-history input)
(goto-char (point-max))
(insert ?\n)
(add-text-properties prompt-end (point-max)
(list 'read-only t
'rear-nonsticky t))
(racket--repl-delete-prompt-mark nil)
(racket--cmd/async (racket--repl-session-id) `(repl-submit ,input+ret))))
(end-of-line)
(when (< racket--repl-output-mark (point))
(let ((input (buffer-substring-no-properties racket--repl-output-mark (point))))
;; Intentionally do NOT `racket--repl-add-to-input-history'.
(insert ?\n)
(add-text-properties racket--repl-output-mark (point)
(list 'read-only t
'rear-nonsticky t))
(set-marker racket--repl-output-mark (point))
(racket--cmd/async (racket--repl-session-id)
`(repl-input ,(concat input "\n"))))))))
(defun racket--repl-complete-sexp-p ()
"Is there at least one complete sexp at REPL prompt?"
(condition-case _
(let* ((beg (racket--repl-prompt-mark-end))
(end (save-excursion
(goto-char beg)
(while (< (point) (point-max))
;; This will scan-error unless complete sexp, or
;; all whitespace.
(forward-list 1))
(point))))
(not (or (equal beg end) ;nothing
(string-match-p ;something but all whitespace
(rx bos
(1+ (or (syntax whitespace)
(syntax comment-start)
(syntax comment-end)))
eos)
(buffer-substring beg end)))))
(scan-error nil)))
(defun racket-repl-break ()
"Send an interrupt break to the REPL."
(interactive)
(unless (racket--cmd-open-p) ;don't auto-start the back end
(user-error "Back end is not running"))
(racket--cmd/async (racket--repl-session-id) `(repl-break)))
(defun racket-repl-exit ()
"Exit the REPL session.
Equivalent to entering \"(exit)\" at the REPL prompt, but works
even when the module language doesn't provide any binding for
\"exit\"."
(interactive)
;; Avoid sending a command about exiting a REPL session that can't
;; exist because the back end isn't running. That's worse than a
;; no-op; that would auto-start the back end for no good reason now.
(when (racket--cmd-open-p)
(when (racket--repl-session-id)
;; Note: We don't `(setq racket--repl-session-id nil)` here
;; because (1) the repl buffer isn't necessarily current and
;; anyway (2) we want to allow our output handler function to
;; get the "exit" message from the back end; it will set nil,
;; then.
(racket--cmd/async (racket--repl-session-id) `(repl-exit)))))
(declare-function racket-repl-buffer-name-unique "racket-repl-buffer-name" ())
(autoload 'racket-repl-buffer-name-unique "racket-repl-buffer-name")
(declare-function racket-mode "racket-mode" ())
(autoload 'racket-mode "racket-mode")
;;;###autoload
(defun racket-repl (&optional noselect)
"Show a Racket REPL buffer in some window.
The intended use of Racket Mode's REPL is that you `find-file'
some specific file, then run it using a command like `racket-run'
or `racket-run-module-at-point'. The resulting REPL will
correspond to those definitions and match your expectations.
Therefore this `racket-repl' command -- which is intended as a
convenience for people who want to \"just get a quick scratch
REPL\" -- is actually implemented as running the file named in
the customization variable `racket-repl-command-file'. When that
file doesn't exist, it is created to contain just \"#lang
racket/base\". You may edit the file to use a different lang,
require other modules, or whatever."
(interactive "P")
;; Create file if it doesn't exist
(unless (file-exists-p racket-repl-command-file)
(let ((dir (file-name-directory racket-repl-command-file)))
(unless (file-exists-p dir)
(make-directory dir t)))
(write-region ";; Used by M-x racket-repl; you may edit\n#lang racket/base\n"
nil racket-repl-command-file))
;; Visit the file without selecting it, and run it.
(let ((racket-repl-buffer-name-function #'racket-repl-buffer-name-unique))
(with-current-buffer (find-file-noselect racket-repl-command-file)
(unless (racket--edit-mode-p)
(racket-mode)) ;ensure: see #713
(racket--repl-run
(list racket-repl-command-file)
nil
nil
(lambda ()
(display-buffer racket-repl-buffer-name)
(unless noselect
(select-window (get-buffer-window racket-repl-buffer-name t))))))))
;;; Run
;; Note: These commands are to be run when current-buffer is a
;; `racket-mode' buffer. The reason they are defined here is because
;; they use a `racket-repl-mode' buffer, and, one could use
;; `racket-mode' to edit files without using these commands.
;;;###autoload
(defun racket-run (&optional prefix)
"Save the buffer in REPL and run your program.
As well as evaluating the outermost, file module, automatically
runs the submodules specified by the customization variable
`racket-submodules-to-run'.
See also `racket-run-module-at-point', which runs just the
specific module at point.
The command varies based on how many \\[universal-argument]
prefix arguments you supply.
\\<racket-mode-map>
- \\[racket-run-and-switch-to-repl]
Follows the `racket-error-context' setting.
- \\[universal-argument] \\[racket-run-and-switch-to-repl]
Uses errortrace for improved stack traces, as if
`racket-error-context' were set to \"high\".
This lets you keep `racket-error-context' set to a faster
value like \"low\" or \"medium\", then conveniently re-run
when you need a better strack trace.
- \\[universal-argument] \\[universal-argument] \\[racket-run-and-switch-to-repl]
Instruments code for step debugging. See `racket-debug-mode'
and the variable `racket-debuggable-files'.
Each run occurs within a Racket custodian. Any prior run's
custodian is shut down, releasing resources like threads and
ports. Each run's evaluation environment is reset to the contents
of the source file. In other words, like Dr Racket, this provides
the benefit that your source file is the \"single source of
truth\". At the same time, the run gives you a REPL inside the
namespace of the module, giving you the ability to explore it
interactively. Any explorations are temporary, unless you also
make them to your source file, they will be lost on the next run.
See also `racket-run-and-switch-to-repl', which is even more like
Dr Racket's Run command because it selects the REPL window after
running.
To visit error locations, move point there and press RET or mouse
click. Or, use the standard `next-error' and `previous-error'
commands from either the edit or REPL buffer."
(interactive "P")
(racket--repl-run (list (racket--buffer-file-name))
racket-submodules-to-run
(pcase prefix
(`(4) 'high)
(`(16) 'debug)
(_ racket-error-context))))
;;;###autoload
(defun racket-run-module-at-point (&optional prefix)
"Save the buffer and run the module at point.
Like `racket-run' but runs the innermost module around point,
which is determined textually by looking for \"module\",
\"module*\", or \"module+\" forms nested to any depth, else
simply the outermost, file module."
(interactive "P")
(racket--repl-run (racket--what-to-run)
'()
(pcase prefix
(`(4) 'high)
(`(16) 'debug)
(_ racket-error-context))))
(defun racket-run-with-errortrace ()
"Run with `racket-error-context' temporarily set to \"high\".
\\<racket-mode-map>
This is equivalent to \\[universal-argument] \\[racket-run].
Defined as a function so it can be a menu target."
(interactive)
(racket-run '(4)))
(defun racket-run-with-debugging ()
"Run with `racket-error-context' temporarily set to \"debug\".
\\<racket-mode-map>
This is equivalent to \\[universal-argument] \\[universal-argument] \\[racket-run].
Defined as a function so it can be a menu target."
(interactive)
(racket-run '(16)))
(defun racket-run-and-switch-to-repl (&optional prefix)
"This is `racket-run' followed by selecting the REPL buffer window.
This is similar to how Dr Racket behaves.
\\<racket-mode-map>
To make it even more similar, you may add `racket-repl-clear' to
the variable `racket-before-run-hook'."
(interactive "P")
(racket--repl-run (list (racket--buffer-file-name))
racket-submodules-to-run
(pcase prefix
(`(4) 'high)
(`(16) 'debug)
(_ racket-error-context))
#'racket-edit-switch-to-repl))
(defun racket-test (&optional prefix)
"Run the \"test\" submodule.
Put your tests in a \"test\" submodule. For example:
#+BEGIN_SRC racket
(module+ test
(require rackunit)
(check-true #t))
#+END_SRC
Any rackunit test failure messages show the location. You may use
`next-error' to jump to the location of each failing test.
With \\[universal-argument] uses errortrace for improved stack traces.
Otherwise follows the `racket-error-context' setting.
With \\[universal-argument] \\[universal-argument] also runs the
tests with coverage instrumentation and highlights uncovered code
using `font-lock-warning-face'.
See also:
- `racket-fold-all-tests'
- `racket-unfold-all-tests'
"
(interactive "P")
(let ((mod-path (list (racket--buffer-file-name) 'test))
(buf (current-buffer)))
;; Originally this function's single optional argument was a
;; `coverage-p` boolean. For backward compatibility in case anyone
;; has Emacs Lisp calling this function non-interactively, we keep
;; supporting t and nil values.
(pcase prefix
(`() (racket--repl-run mod-path))
(`(4) (racket--repl-run mod-path nil 'high))
((or '(16) 't)
(message "Running test submodule with coverage instrumentation...")
(racket--repl-run
mod-path
nil
'coverage
(lambda ()
(message "Getting coverage results...")
(racket--cmd/async
(racket--repl-session-id)
`(get-uncovered)
(lambda (xs)
(pcase xs
(`() (message "Full coverage."))
((and xs `((,beg0 . ,_) . ,_))
(message "Missing coverage in %s place(s)." (length xs))
(with-current-buffer buf
(with-silent-modifications
(overlay-recenter (point-max))
(dolist (x xs)
(let ((o (make-overlay (car x) (cdr x) buf)))
(overlay-put o 'name 'racket-uncovered-overlay)
(overlay-put o 'priority 100)
(overlay-put o 'face font-lock-warning-face)))
(goto-char beg0)))))))))))))
(add-hook 'racket--repl-before-run-hook #'racket--remove-coverage-overlays)
(defun racket--remove-coverage-overlays ()
(remove-overlays (point-min) (point-max) 'name 'racket-uncovered-overlay))
(defvar-local racket-user-command-line-arguments
nil
"List of command-line arguments to supply to your Racket program.
Accessible in your Racket program in the usual way --- the
parameter `current-command-line-arguments` and friends.
This is an Emacs buffer-local variable --- convenient to set as a
file local variable. For example at the end of your .rkt file:
#+BEGIN_SRC elisp
;; Local Variables:
;; racket-user-command-line-arguments: (\"-f\" \"bar\")
;; End:
#+END_SRC
Set this way, the value must be an *unquoted* list of strings.
For example:
#+BEGIN_SRC elisp
(\"-f\" \"bar\")
#+END_SRC
The following values will /not/ work:
#+BEGIN_SRC elisp
\\='(\"-f\" \"bar\")
(list \"-f\" \"bar\")
#+END_SRC
")
(defvar racket--repl-before-run-hook nil
"Thunks to do before each `racket--repl-run'.
Here \"before\" means that the `racket-repl-mode' buffer might not
exist yet.
This hook is for internal use by Racket Mode. An equivalent hook
for end user customization is `racket-before-run-hook'.")
(defvar racket--repl-after-run-hook nil
"Thunks to do after each `racket--repl-run'.
This hook is for internal use by Racket Mode. An equivalent hook
for end user customization is `racket-after-run-hook'.
Here \"after\" means that the run has completed and e.g. the REPL
is waiting at another prompt.")
;; Don't (require 'racket-hash-lang). Mutual dependency. Instead:
(declare-function racket--configure-repl-buffer-from-edit-buffer "racket-hash-lang" (edit-buf repl-buf))
(autoload 'racket--configure-repl-buffer-from-edit-buffer "racket-hash-lang")
(defun racket--repl-run (&optional what extra-submods context-level callback)
"Do an initial or subsequent run.
WHAT must be `racket--what-to-run-p', where nil defaults to
`racket--what-to-run'.
EXTRA-SUBMODS should be a list of symbols, names of extra
submodules to run, e.g. (test main). This is intended for use by
`racket-run', which more closely emulates DrRacket, as opposed to
`racket-run-module-at-point'.
CONTEXT-LEVEL should be a valid value for the variable
`racket-error-context', \"coverage\", or \"profile\". Or if nil,
defaults to the variable `racket-error-context'.
CALLBACK is used as the callback for `racket--cmd/async'; it may
be nil which is equivalent to #\\='ignore."
(racket--assert-edit-mode)
;; Support running buffers created by `org-edit-src-code': see
;; issues #626, #630.
(when (bound-and-true-p org-src-mode)
(unless buffer-file-name
;; Give the buffer a temp file we can run. The correct thing to
;; use is `set-visited-file-name', which handles many things
;; besides setting `buffer-file-name'. Some we want, e.g.
;; setting the buffer-modified flag. Some we don't, e.g.
;; renaming the buffer, which we rename back to the original
;; because org-src does things with regexps on these buffer
;; names.
(let ((orig-buffer-name (buffer-name)))
(set-visited-file-name (make-temp-file "racket-org-edit-" nil ".rkt"))
(rename-buffer orig-buffer-name))
(setq what (list (racket--buffer-file-name)))
;; org-src adds to `write-contents-functions' a hook that
;; prevents `save-buffer' actually writing to file; instead it
;; copies contents back to the main org buffer. Accommodate that
;; by prepending our own hook, which actually writes to file. It
;; returns nil to mean other hooks should still be run, so this
;; doesn't interfere with org's hook.
(add-hook 'write-contents-functions #'racket--write-contents nil t)))
;; Save buffer and validate WHAT to run.
(unless (progn (racket--save-if-changed)
(racket--what-to-run-p what))
(signal 'wrong-type-argument `(racket--what-to-run-p ,what)))
;; Handle the restart-watch-directories feature; #602
(when-let (changes (racket--back-end-watch-read/reset))
(when (y-or-n-p (format "Changed: %S -- restart Racket Mode back end %S? "
changes
(racket-back-end-name)))
(message "")
(racket-start-back-end)))
(pcase-let*
((context-level (or context-level racket-error-context))
(what (or what (racket--what-to-run)))
(`(,what ,debug-files)
(pcase what
(`(,file . ,subs)
(list (cons (racket-file-name-front-to-back file) subs)
(when (eq context-level 'debug)
(racket--debuggable-files file))))
(`()
(list nil nil))))
(cmd (list 'run
what
extra-submods
racket-memory-limit
racket-pretty-print
(window-width)
(racket--char-pixel-width)
context-level
racket-user-command-line-arguments
debug-files))
(edit-buffer (current-buffer))
(after (lambda (_ignore)
(with-current-buffer edit-buffer
(run-hooks 'racket--repl-after-run-hook
'racket-after-run-hook)
(when callback
(funcall callback))))))
(racket--repl-ensure-buffer-and-session
edit-buffer
(lambda (_repl-buffer)
(with-current-buffer edit-buffer
(run-hooks 'racket--repl-before-run-hook
'racket-before-run-hook))
(racket--cmd/async (racket--repl-session-id) cmd after)))))
(defun racket--write-contents ()
(write-region nil nil buffer-file-name)
nil)
(defun racket--char-pixel-width ()
(with-temp-buffer
(insert "M")
(save-window-excursion
(set-window-buffer nil (current-buffer))
(car (window-text-pixel-size nil (line-beginning-position) (point))))))
(defun racket--repl-ensure-buffer-and-session (edit-buffer continue)
"Ensure a `racket-repl-mode' buffer exists with a live session.
Create the buffer if necessary, enabling `racket-repl-mode'.
Start the session if necessary.
When EDIT-BUFFER is not nil, use it to call
`racket--configure-repl-buffer-from-edit-buffer' after the repl
buffer is fully initialized (and if the repl session isn't
started, before starting it).
Calls CONTINUE with one argument, the repl buffer.
This displays the buffer but does not change the selected window."
(let ((repl-buf (or (get-buffer racket-repl-buffer-name)
(with-current-buffer (get-buffer-create racket-repl-buffer-name)
(racket-repl-mode)
(add-hook 'kill-buffer-hook #'racket-repl-exit nil t)
(current-buffer)))))
(display-buffer repl-buf)
(with-current-buffer repl-buf
(if racket--repl-session-id
(progn
(when edit-buffer
(racket--configure-repl-buffer-from-edit-buffer edit-buffer repl-buf))
(funcall continue repl-buf))
(setq racket--repl-session-id (cl-incf racket--repl-next-session-id))
(when noninteractive
(princ (format "{racket--repl-start}: picked next session id %S\n"
racket--repl-session-id)))
(goto-char (point-max))
(racket--repl-delete-prompt-mark t)
(setq racket--repl-run-mark (point-marker))
(setq racket--repl-output-mark (point-marker))
(set-marker-insertion-type racket--repl-output-mark nil)
(when edit-buffer
(racket--configure-repl-buffer-from-edit-buffer edit-buffer repl-buf))
(unless (racket--cmd-open-p)
(racket--repl-insert-output 'message "Starting back end..."))
(racket--cmd/async nil
`(repl-start ,racket--repl-session-id)
(lambda (_id)
(funcall continue repl-buf)))))))
;;; Switch between associcated edit and REPL buffers
(defun racket-edit-switch-to-repl ()
"Select REPL buffer associated with the edit buffer.
When no such buffer exists yet, do nothing but say so and suggest
using a run command."
(interactive)
(racket--assert-edit-mode)
(pcase (get-buffer racket-repl-buffer-name)
((and repl-buf (pred buffer-live-p))
(display-buffer repl-buf)
(select-window (get-buffer-window repl-buf t)))
(_ (user-error
(format "No REPL buffer exists for %s; use a run command"
(buffer-name))))))
(defun racket-repl-file-name ()
"Return the file running in the REPL, or nil.
The result can be nil if the REPL is not started."
(when (racket--repl-session-id)
(racket--cmd/await (racket--repl-session-id) `(path))))
(defun racket--in-repl-or-its-file-p ()
"Is current-buffer `racket-repl-mode' or buffer for file active in it?"
(or (eq (current-buffer)
(get-buffer racket-repl-buffer-name))
(let ((buf-file (racket--buffer-file-name))
(repl-file (racket-repl-file-name)))
(and buf-file repl-file (string-equal buf-file repl-file)))))
(defun racket-repl-switch-to-edit ()
"Select edit buffer of the file running in the REPL.
If no buffer is visting the file, `find-file' it in `other-window'."
(interactive)
(pcase (racket-repl-file-name)
((and (pred stringp) path)
(pcase (find-buffer-visiting path)
((and (pred bufferp) buffer) (pop-to-buffer buffer t))
(_ (other-window 1)
(find-file path))))
(_ (pcase (racket--most-recent-edit-buffer)
((and (pred bufferp) buffer) (pop-to-buffer buffer t))
(_ (user-error "There are no racket-mode buffers"))))))
(defun racket--most-recent-edit-buffer ()
(cl-some (lambda (b)
(with-current-buffer b
(and (racket--edit-mode-p) b)))
(buffer-list)))
;;; send to REPL
(defun racket--send-region-to-repl (start end &optional echo-p)
"Internal function to send the region to the Racket REPL.
Requires the REPL already to be started, e.g. from a run command.
Before sending the region, calls `racket--repl-forget-errors'.
Also inserts a ?\n at the process mark so that output goes on a
fresh line, not on the same line as the prompt.