summaryrefslogtreecommitdiff
path: root/elisp/geiser-repl.el
blob: e74a187a49d03e39d4ac288d79b238da9a9359fe (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
;;; geiser-repl.el --- Geiser's REPL

;; Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2016, 2018, 2019, 2020, 2021 Jose Antonio Ortega Ruiz

;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the Modified BSD License. You should
;; have received a copy of the license along with this program. If
;; not, see <http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5>.


;;; Code:

(require 'geiser-company)
(require 'geiser-doc)
(require 'geiser-autodoc)
(require 'geiser-edit)
(require 'geiser-completion)
(require 'geiser-syntax)
(require 'geiser-impl)
(require 'geiser-eval)
(require 'geiser-connection)
(require 'geiser-menu)
(require 'geiser-image)
(require 'geiser-custom)
(require 'geiser-base)

(require 'comint)
(require 'compile)
(require 'scheme)
(require 'font-lock)


;;; Customization:

(defgroup geiser-repl nil
  "Interacting with the Geiser REPL."
  :group 'geiser)

(geiser-custom--defcustom geiser-repl-buffer-name-function
    'geiser-repl-buffer-name
  "Function used to define the name of a REPL buffer.
The function is called with a single argument - an implementation
symbol (e.g., `guile', `chicken', etc.)."
  :type '(choice (function-item geiser-repl-buffer-name)
                 (function :tag "Other function")))

(geiser-custom--defcustom geiser-repl-current-project-function
    (if (featurep 'project) #'project-current 'ignore)
  "Function used to determine the current project.
The function is called from both source and REPL buffers, and
should return a value which uniquely identifies the project."
  :type '(choice (function-item :tag "Ignore projects" ignore)
                 (function-item :tag "Use Project.el" project-current)
                 (function-item :tag "Use Projectile" projectile-project-root)
                 (function :tag "Other function")))

(geiser-custom--defcustom geiser-repl-use-other-window t
  "Whether to Use a window other than the current buffer's when
switching to the Geiser REPL buffer."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-window-allow-split t
  "Whether to allow window splitting when switching to the Geiser REPL buffer."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-history-filename
    (expand-file-name "~/.geiser_history")
  "File where REPL input history is saved, so that it persists between sessions.

This is actually the base name: the concrete Scheme
implementation name gets appended to it."
  :type 'file)

(geiser-custom--defcustom geiser-repl-history-size comint-input-ring-size
  "Maximum size of the saved REPL input history."
  :type 'integer)

(geiser-custom--defcustom geiser-repl-history-no-dups-p t
  "Whether to skip duplicates when recording history."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-save-debugging-history-p nil
  "Whether to skip debugging input in REPL history.

By default, REPL interactions while scheme is in the debugger are
not added to the REPL command history.  Set this variable to t to
change that."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-autodoc-p t
  "Whether to enable `geiser-autodoc-mode' in the REPL by default."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-company-p t
  "Whether to use company-mode for completion, if available."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-read-only-prompt-p t
  "Whether the REPL's prompt should be read-only."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-read-only-output-p t
  "Whether the REPL's output should be read-only."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-highlight-output-p nil
  "Whether to syntax highlight REPL output."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-auto-indent-p t
  "Whether newlines for incomplete sexps are autoindented."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-send-on-return-p t
  "Sends input to REPL when ENTER is pressed in a balanced S-expression,
regardless of cursor positioning.

When off, pressing ENTER inside a balance S-expression will
introduce a new line without sending input to the inferior
Scheme process. This option is useful when using minor modes
which might do parentheses balancing, or when entering additional
arguments inside an existing expression.

When on (the default), pressing ENTER inside a balanced S-expression
will send the input to the inferior Scheme process regardless of the
cursor placement."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-forget-old-errors-p t
  "Whether to forget old errors upon entering a new expression.

When on (the default), every time a new expression is entered in
the REPL old error messages are flushed, and using \\[next-error]
afterwards will jump only to error locations produced by the new
expression, if any."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-skip-version-check-p nil
  "Whether to skip version checks for the Scheme executable.

When set, Geiser won't check the version of the Scheme
interpreter when starting a REPL, saving a few tenths of a
second."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-query-on-exit-p nil
  "Whether to prompt for confirmation on \\[geiser-repl-exit]."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-delete-last-output-on-exit-p nil
  "Whether to delete partial outputs when the REPL's process exits."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-query-on-kill-p t
  "Whether to prompt for confirmation when killing a REPL buffer with
a life process."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-default-host "localhost"
  "Default host when connecting to remote REPLs."
  :type 'string)

(geiser-custom--defcustom geiser-repl-default-port 37146
  "Default port for connecting to remote REPLs."
  :type 'integer)

(geiser-custom--defcustom geiser-repl-startup-time 10000
  "Time, in milliseconds, to wait for Racket to startup.
If you have a slow system, try to increase this time."
  :type 'integer)

(geiser-custom--defcustom geiser-repl-inline-images-p t
  "Whether to display inline images in the REPL."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-auto-display-images-p t
  "Whether to automatically invoke the external viewer to display
images popping up in the REPL.

See also `geiser-debug-auto-display-images-p'."
  :type 'boolean)

(geiser-custom--defcustom geiser-repl-add-project-path-p t
  "Whether to automatically add current project's root to load path on startup.
For this option to take effect,
`geiser-repl-current-project-function' must be set appropriately."
  :type 'boolean)

(geiser-custom--defface repl-input
  'comint-highlight-input geiser-repl "evaluated input highlighting")

(geiser-custom--defface repl-output
  'font-lock-string-face geiser-repl "REPL output")

(geiser-custom--defface repl-prompt
  'comint-highlight-prompt geiser-repl "REPL prompt")



;;; Implementation-dependent parameters

(geiser-impl--define-caller geiser-repl--binary binary ()
  "A variable or function returning the path to the scheme binary
for this implementation.")

(geiser-impl--define-caller geiser-repl--arglist arglist ()
  "A function taking no arguments and returning a list of
arguments to be used when invoking the scheme binary.")

(geiser-impl--define-caller geiser-repl--prompt-regexp prompt-regexp ()
  "A variable (or thunk returning a value) giving the regular
expression for this implementation's geiser scheme prompt.")

(geiser-impl--define-caller
    geiser-repl--debugger-prompt-regexp debugger-prompt-regexp ()
  "A variable (or thunk returning a value) giving the regular
expression for this implementation's debugging prompt.")

(geiser-impl--define-caller geiser-repl--startup repl-startup (remote)
  "Function taking no parameters that is called after the REPL
has been initialised. All Geiser functionality is available to
you at that point.")

(geiser-impl--define-caller geiser-repl--enter-cmd enter-command (module)
  "Function taking a module designator and returning a REPL enter
module command as a string")

(geiser-impl--define-caller geiser-repl--import-cmd import-command (module)
  "Function taking a module designator and returning a REPL import
module command as a string")

(geiser-impl--define-caller geiser-repl--exit-cmd exit-command ()
  "Function returning the REPL exit command as a string")

(geiser-impl--define-caller geiser-repl--version version-command (binary)
  "Function returning the version of the corresponding scheme process,
   given its full path.")

(geiser-impl--define-caller geiser-repl--min-version minimum-version ()
  "A variable providing the minimum required scheme version, as a string.")


;;; Geiser REPL buffers and processes:

(defvar geiser-repl--repls nil)
(defvar geiser-repl--closed-repls nil)

(defvar geiser-repl--last-output-start nil)
(defvar geiser-repl--last-output-end nil)

(defvar-local geiser-repl--repl nil)

(defvar-local geiser-repl--project nil)

(defsubst geiser-repl--set-this-buffer-repl (r)
  (setq geiser-repl--repl r))

(defsubst geiser-repl--set-this-buffer-project (p)
  (setq geiser-repl--project p))

(defsubst geiser-repl--current-project ()
  (or (funcall geiser-repl-current-project-function)
      'no-project))

(defun geiser-repl--live-p ()
  (and geiser-repl--repl
       (get-buffer-process geiser-repl--repl)))

(defun geiser-repl--repl/impl (impl &optional proj repls)
  (let ((proj (or proj
                  geiser-repl--project
                  (geiser-repl--current-project)))
        (repls (or repls
                   geiser-repl--repls)))
    (catch 'repl
      (dolist (repl repls)
        (when (buffer-live-p repl)
          (with-current-buffer repl
            (when (and (eq geiser-impl--implementation impl)
                       (equal geiser-repl--project proj))
              (throw 'repl repl))))))))

(defun geiser-repl--set-up-repl (impl)
  (or (and (not impl) geiser-repl--repl)
      (setq geiser-repl--repl
            (let ((impl (or impl
                            geiser-impl--implementation
                            (geiser-impl--guess))))
              (when impl (geiser-repl--repl/impl impl))))))

(defun geiser-repl--active-impls ()
  (let ((act))
    (dolist (repl geiser-repl--repls act)
      (with-current-buffer repl
        (add-to-list 'act geiser-impl--implementation)))))

(defsubst geiser-repl--repl-name (impl)
  (format "%s REPL" (geiser-impl--impl-str impl)))

(defsubst geiser-repl--buffer-name (impl)
  (funcall geiser-repl-buffer-name-function impl))

(defun geiser-repl-buffer-name (impl)
  "Return default name of the REPL buffer for implementation IMPL."
  (format "* %s *" (geiser-repl--repl-name impl)))

(defun geiser-repl--switch-to-buffer (buffer)
  (unless (eq buffer (current-buffer))
    (let ((pop-up-windows geiser-repl-window-allow-split))
      (if geiser-repl-use-other-window
          (switch-to-buffer-other-window buffer)
        (switch-to-buffer buffer)))))

(defun geiser-repl--to-repl-buffer (impl)
  (unless (and (eq major-mode 'geiser-repl-mode)
               (eq geiser-impl--implementation impl)
               (not (get-buffer-process (current-buffer))))
    (let* ((proj (geiser-repl--current-project))
           (old (geiser-repl--repl/impl impl proj geiser-repl--closed-repls))
           (old (and (buffer-live-p old)
                     (not (get-buffer-process old))
                     old)))
      (geiser-repl--switch-to-buffer
       (or old (generate-new-buffer (geiser-repl--buffer-name impl))))
      (unless old
        (geiser-repl-mode)
        (geiser-impl--set-buffer-implementation impl)
        (geiser-repl--set-this-buffer-project proj)
        (geiser-syntax--add-kws t)))))

(defun geiser-repl--read-impl (prompt &optional active)
  (geiser-impl--read-impl prompt (and active (geiser-repl--active-impls))))

(defsubst geiser-repl--only-impl-p ()
  (and (null (cdr geiser-active-implementations))
       (car geiser-active-implementations)))

(defun geiser-repl--get-impl (prompt)
  (or (geiser-repl--only-impl-p)
      (and (eq major-mode 'geiser-repl-mode) geiser-impl--implementation)
      (geiser-repl--read-impl prompt)))


;;; Prompt &co.

(defun geiser-repl--last-prompt-end ()
  (cond ((and (boundp 'comint-last-prompt) (markerp (cdr comint-last-prompt)))
         (marker-position (cdr comint-last-prompt)))
        ((and (boundp 'comint-last-prompt-overlay) comint-last-prompt-overlay)
         (overlay-end comint-last-prompt-overlay))
        (t (save-excursion
             (geiser-repl--bol)
             (min (+ 1 (point)) (point-max))))))

(defun geiser-repl--last-prompt-start ()
  (cond ((and (boundp 'comint-last-prompt) (markerp (car comint-last-prompt)))
         (marker-position (car comint-last-prompt)))
        ((and (boundp 'comint-last-prompt-overlay) comint-last-prompt-overlay)
         (overlay-start comint-last-prompt-overlay))
        (t (save-excursion (geiser-repl--bol) (point)))))


;;; REPL connections

(defvar-local geiser-repl--address nil)

(defvar-local geiser-repl--connection nil)

(defun geiser-repl--local-p ()
  "Return non-nil, if current REPL is local (connected to socket)."
  (stringp geiser-repl--address))

(defun geiser-repl--remote-p ()
  "Return non-nil, if current REPL is remote (connected to host:port)."
  (consp geiser-repl--address))

(defsubst geiser-repl--host () (car geiser-repl--address))
(defsubst geiser-repl--port () (cdr geiser-repl--address))

(defun geiser-repl--read-address (&optional host port)
  (let ((defhost (or (geiser-repl--host) geiser-repl-default-host))
        (defport (or (geiser-repl--port) geiser-repl-default-port)))
    (cons (or host
              (read-string (format "Host (default %s): " defhost)
                           nil nil defhost))
          (or port (read-number "Port: " defport)))))

(defun geiser-repl--autodoc-mode (n)
  (when (or geiser-repl-autodoc-p (< n 0))
    (geiser--save-msg (geiser-autodoc-mode n))))

(defun geiser-repl--save-remote-data (address)
  (setq geiser-repl--address address)
  (cond ((consp address)
         (setq header-line-format
               (format "Host: %s   Port: %s"
                       (geiser-repl--host)
                       (geiser-repl--port))))
        ((stringp address)
         (setq header-line-format
               (format "Socket: %s" address)))))

(defun geiser-repl--fontify-output-region (beg end)
  "Apply highlighting to a REPL output region."
  (remove-text-properties beg end '(font-lock-face nil face nil))
  (if geiser-repl-highlight-output-p
      (geiser-syntax--fontify-syntax-region beg end)
    (geiser-repl--fontify-plaintext beg end)))

(defun geiser-repl--fontify-plaintext (start end)
  "Fontify REPL output plainly."
  (add-text-properties
   start end
   '(font-lock-fontified t
			 fontified t
			 font-lock-multiline t
			 font-lock-face geiser-font-lock-repl-output)))

(defun geiser-repl--narrow-to-prompt ()
  "Narrow to active prompt region and return t, otherwise returns nil."
  (let* ((proc (get-buffer-process (current-buffer)))
         (pmark (and proc (process-mark proc)))
         (intxt (when (>= (point) (marker-position pmark))
                  (save-excursion
                    (if comint-eol-on-send
                        (if comint-use-prompt-regexp
                            (end-of-line)
                          (goto-char (field-end))))
                    (buffer-substring pmark (point)))))
         (prompt-beg (marker-position pmark))
         (prompt-end (+ prompt-beg (length intxt))))
    (when (> (length intxt) 0)
      (narrow-to-region prompt-beg prompt-end)
      t)))

(defun geiser-repl--wrap-fontify-region-function (beg end &optional loudly)
  (save-restriction
    (when (geiser-repl--narrow-to-prompt)
      (let ((font-lock-dont-widen t))
        (font-lock-default-fontify-region (point-min) (point-max) nil)))))

(defun geiser-repl--wrap-unfontify-region-function (beg end &optional loudly)
  (save-restriction
    (when (geiser-repl--narrow-to-prompt)
      (let ((font-lock-dont-widen t))
        (font-lock-default-unfontify-region (point-min) (point-max))))))

(defun geiser-repl--find-output-region ()
  (save-excursion
    (goto-char (point-max))
    (re-search-backward comint-prompt-regexp)
    (move-to-column 0)
    (set-marker geiser-repl--last-output-end (point))
    (save-excursion
      (when (re-search-backward comint-prompt-regexp nil t)
        (forward-line)
        (when (> (point) geiser-repl--last-output-start)
          (set-marker geiser-repl--last-output-start (point)))))
    (> (- geiser-repl--last-output-end geiser-repl--last-output-start) 2)))

(defun geiser-repl--treat-output-region ()
  (with-silent-modifications
    (add-text-properties (1- geiser-repl--last-output-start)
                         geiser-repl--last-output-end
                         `(read-only ,geiser-repl-read-only-output-p))
    (geiser-repl--fontify-output-region geiser-repl--last-output-start
                                        geiser-repl--last-output-end)
    (geiser--font-lock-ensure geiser-repl--last-output-start
                              geiser-repl--last-output-end)))

(defun geiser-repl--output-filter (txt)
  (when (geiser-repl--find-output-region) (geiser-repl--treat-output-region))
  (geiser-con--connection-update-debugging geiser-repl--connection txt)
  (geiser-image--replace-images geiser-repl-inline-images-p
                                geiser-repl-auto-display-images-p)
  (when (string-match-p (geiser-con--connection-prompt geiser-repl--connection)
                        txt)
    (geiser-autodoc--disinhibit-autodoc)))

(defun geiser-repl--check-version (impl)
  (when (not geiser-repl-skip-version-check-p)
    (let ((v (geiser-repl--version impl (geiser-repl--binary impl)))
          (r (geiser-repl--min-version impl)))
      (when (and v r (geiser--version< v r))
        (error "Geiser requires %s version %s but detected %s" impl r v)))))

(defvar geiser-repl--last-scm-buffer)

(defun geiser-repl--start-repl (impl address)
  (message "Starting Geiser REPL ...")
  (when (not address) (geiser-repl--check-version impl))
  (let ((buffer (current-buffer))
        (binary (geiser-repl--binary impl))
        (arglist (geiser-repl--arglist impl)))
    (geiser-repl--to-repl-buffer impl)
    (setq geiser-repl--last-scm-buffer buffer
          geiser-repl--binary binary
          geiser-repl--arglist arglist))
  (sit-for 0)
  (goto-char (point-max))
  (geiser-repl--autodoc-mode -1)
  (let* ((prompt-rx (geiser-repl--prompt-regexp impl))
         (deb-prompt-rx (geiser-repl--debugger-prompt-regexp impl))
         (prompt (geiser-con--combined-prompt prompt-rx deb-prompt-rx)))
    (unless prompt-rx
      (error "Sorry, I don't know how to start a REPL for %s" impl))
    (geiser-repl--save-remote-data address)
    (geiser-repl--start-scheme impl address prompt)
    (geiser-repl--quit-setup)
    (geiser-repl--history-setup)
    (add-to-list 'geiser-repl--repls (current-buffer))
    (geiser-repl--set-this-buffer-repl (current-buffer))
    (setq geiser-repl--connection
          (geiser-con--make-connection (get-buffer-process (current-buffer))
                                       prompt-rx
                                       deb-prompt-rx))
    (geiser-repl--startup impl address)
    (geiser-repl--autodoc-mode 1)
    (geiser-company--setup geiser-repl-company-p)
    (when geiser-repl-add-project-path-p
      (when-let (root (funcall geiser-repl-current-project-function))
        (geiser-add-to-load-path (cdr root))))
    (add-hook 'comint-output-filter-functions
              'geiser-repl--output-filter
              nil
              t)
    (set-process-query-on-exit-flag (get-buffer-process (current-buffer))
                                    geiser-repl-query-on-kill-p)
    (message "%s up and running!" (geiser-repl--repl-name impl))))

(defun geiser-repl--start-scheme (impl address prompt)
  (setq comint-prompt-regexp prompt)
  (let* ((name (geiser-repl--repl-name impl))
         (buff (current-buffer))
         (args (cond ((consp address) (list address))
                     ((stringp address) '(()))
                     (t `(,(geiser-repl--get-binary impl)
                          nil
                          ,@(geiser-repl--get-arglist impl))))))
    (condition-case err
        (if (and address (stringp address))
            ;; Connect over a Unix-domain socket.
            (let ((proc (make-network-process :name (buffer-name buff)
                                              :buffer buff
                                              :family 'local
                                              :remote address)))
              ;; brittleness warning: this is stuff
              ;; make-comint-in-buffer sets up, via comint-exec, when
              ;; it creates its own process, something we're doing
              ;; here by ourselves.
              (set-process-filter proc 'comint-output-filter)
              (goto-char (point-max))
              (set-marker (process-mark proc) (point)))
          (apply 'make-comint-in-buffer `(,name ,buff ,@args)))
      (error (insert "Unable to start REPL:\n"
                     (error-message-string err)
                     "\n")
             (error "Couldn't start Geiser: %s" err)))
    (geiser-repl--wait-for-prompt geiser-repl-startup-time)))

(defun geiser-repl--wait-for-prompt (timeout)
  (let ((p (point)) (seen) (buffer (current-buffer)))
    (while (and (not seen)
                (> timeout 0)
                (get-buffer-process buffer))
      (sleep-for 0.1)
      (setq timeout (- timeout 100))
      (goto-char p)
      (setq seen (re-search-forward comint-prompt-regexp nil t)))
    (goto-char (point-max))
    (unless seen (error "%s" "No prompt found!"))))

(defun geiser-repl--is-debugging ()
  (let ((dp (geiser-con--connection-debug-prompt geiser-repl--connection)))
    (and dp
         (save-excursion
           (goto-char (geiser-repl--last-prompt-start))
           (re-search-forward dp (geiser-repl--last-prompt-end) t)))))

(defun geiser-repl--connection* ()
  (let ((buffer (geiser-repl--set-up-repl geiser-impl--implementation)))
    (and (buffer-live-p buffer)
         (get-buffer-process buffer)
         (with-current-buffer buffer geiser-repl--connection))))

(defun geiser-repl--connection ()
  (or (geiser-repl--connection*)
      (error "No Geiser REPL for this buffer (try M-x run-geiser)")))

(setq geiser-eval--default-connection-function 'geiser-repl--connection)

(defun geiser-repl--prepare-send ()
  (geiser-image--clean-cache)
  (geiser-autodoc--inhibit-autodoc)
  (geiser-con--connection-deactivate geiser-repl--connection))

(defun geiser-repl--send (cmd &optional save-history)
  "Send CMD input string to the current REPL buffer.
If SAVE-HISTORY is non-nil, save CMD in the REPL history."
  (when (and cmd (eq major-mode 'geiser-repl-mode))
    (geiser-repl--prepare-send)
    (goto-char (point-max))
    (comint-kill-input)
    (insert cmd)
    (let ((comint-input-filter (if save-history
                                   comint-input-filter
                                 'ignore)))
      (comint-send-input nil t))))

(defun geiser-repl-interrupt ()
  (interactive)
  (when (get-buffer-process (current-buffer))
    (interrupt-process nil comint-ptyp)))


;;; REPL history

(defconst geiser-repl--history-separator "\n}{\n")

(defsubst geiser-repl--history-file ()
  (format "%s.%s" geiser-repl-history-filename geiser-impl--implementation))

(defun geiser-repl--read-input-ring ()
  (let ((comint-input-ring-file-name (geiser-repl--history-file))
        (comint-input-ring-separator geiser-repl--history-separator)
        (buffer-file-coding-system 'utf-8))
    (comint-read-input-ring t)))

(defun geiser-repl--write-input-ring ()
  (let ((comint-input-ring-file-name (geiser-repl--history-file))
        (comint-input-ring-separator geiser-repl--history-separator)
        (buffer-file-coding-system 'utf-8))
    (comint-write-input-ring)))

(defun geiser-repl--history-setup ()
  (set (make-local-variable 'comint-input-ring-size) geiser-repl-history-size)
  (set (make-local-variable 'comint-input-filter) 'geiser-repl--input-filter)
  (geiser-repl--read-input-ring))


;;; Cleaning up

(defun geiser-repl--on-quit ()
  (geiser-repl--write-input-ring)
  (let ((cb (current-buffer))
        (impl geiser-impl--implementation)
        (comint-prompt-read-only nil))
    (geiser-con--connection-deactivate geiser-repl--connection t)
    (geiser-con--connection-close geiser-repl--connection)
    (setq geiser-repl--repls (remove cb geiser-repl--repls))
    (dolist (buffer (buffer-list))
      (when (buffer-live-p buffer)
        (with-current-buffer buffer
          (when (and (eq geiser-impl--implementation impl)
                     (equal cb geiser-repl--repl))
            (geiser-repl--set-up-repl geiser-impl--implementation)))))))

(defun geiser-repl--sentinel (proc event)
  (let ((pb (process-buffer proc)))
    (when (buffer-live-p pb)
      (with-current-buffer pb
        (let ((comint-prompt-read-only nil)
              (comint-input-ring-file-name (geiser-repl--history-file))
              (comint-input-ring-separator geiser-repl--history-separator))
          (geiser-repl--on-quit)
          (push pb geiser-repl--closed-repls)
          (goto-char (point-max))
          (when geiser-repl-delete-last-output-on-exit-p
            (comint-kill-region comint-last-input-start (point)))
          (insert "\nIt's been nice interacting with you!\n")
          (insert
           (substitute-command-keys
            "Press \\[switch-to-geiser] to bring me back.\n")))))))

(defun geiser-repl--on-kill ()
  (geiser-repl--on-quit)
  (setq geiser-repl--closed-repls
        (remove (current-buffer) geiser-repl--closed-repls)))

(defun geiser-repl--input-filter (str)
  (not (or (and (not geiser-repl-save-debugging-history-p)
                (geiser-repl--is-debugging))
           (string-match "^\\s *$" str)
           (string-match "^,quit *$" str))))

(defun geiser-repl--old-input ()
  (save-excursion
    (let ((end (point)))
      (backward-sexp)
      (buffer-substring (point) end))))

(defun geiser-repl--quit-setup ()
  (add-hook 'kill-buffer-hook 'geiser-repl--on-kill nil t)
  (set-process-sentinel (get-buffer-process (current-buffer))
                        'geiser-repl--sentinel))


;;; geiser-repl mode:

(defun geiser-repl--bol ()
  (interactive)
  (when (= (point) (comint-bol)) (beginning-of-line)))

(defun geiser-repl--beginning-of-defun ()
  (save-restriction
    (narrow-to-region (geiser-repl--last-prompt-end) (point))
    (let ((beginning-of-defun-function nil))
      (beginning-of-defun))))

(defun geiser-repl--module-function (&optional module)
  (if (and module geiser-eval--get-impl-module)
      (funcall geiser-eval--get-impl-module module)
    :f))

(defun geiser-repl--doc-module ()
  (interactive)
  (let ((geiser-eval--get-module-function
         (geiser-impl--method 'find-module geiser-impl--implementation)))
    (geiser-doc-module)))

(defun geiser-repl--newline-and-indent ()
  (interactive)
  (save-restriction
    (narrow-to-region comint-last-input-start (point-max))
    (insert "\n")
    (lisp-indent-line)))

(defun geiser-repl--nesting-level ()
  (save-restriction
    (narrow-to-region (geiser-repl--last-prompt-end) (point-max))
    (geiser-syntax--nesting-level)))

(defun geiser-repl--is-input ()
  (not (eq (field-at-pos (point)) 'output)))

(defun geiser-repl--grab-input ()
  (let ((pos (comint-bol)))
    (goto-char (point-max))
    (insert (field-string-no-properties pos))))

(defun geiser-repl--send-input ()
  (set-marker geiser-repl--last-output-start (point-max))

  (let* ((proc (get-buffer-process (current-buffer)))
         (pmark (and proc (process-mark proc)))
         (intxt (and pmark (buffer-substring pmark (point))))
         (eob (point-max)))
    (when intxt
      (when geiser-repl-forget-old-errors-p
        (compilation-forget-errors))
      (geiser-repl--prepare-send)
      (comint-send-input)
      (when (string-match "^\\s-*$" intxt)
        (comint-send-string proc (geiser-eval--scheme-str '(:ge no-values)))
        (comint-send-string proc "\n")))))

(defun geiser-repl--maybe-send ()
  (interactive)
  (let ((p (point)))
    (cond ((< p (geiser-repl--last-prompt-start))
           (if (geiser-repl--is-input)
               (geiser-repl--grab-input)
             (ignore-errors (compile-goto-error))))
          ((let ((inhibit-field-text-motion t))
             (when geiser-repl-send-on-return-p
               (end-of-line))
             (<= (geiser-repl--nesting-level) 0))
           (geiser-repl--send-input))
          (t (goto-char p)
             (if geiser-repl-auto-indent-p
                 (geiser-repl--newline-and-indent)
               (insert "\n"))))))

(defun geiser-repl-tab-dwim (n)
  "If we're after the last prompt, complete symbol or indent (if
there's no symbol at point). Otherwise, go to next error in the REPL
buffer."
  (interactive "p")
  (if (>= (point) (geiser-repl--last-prompt-end))
      (or (completion-at-point)
          (lisp-indent-line))
    (compilation-next-error n)))

(defun geiser-repl--previous-error (n)
  "Go to previous error in the REPL buffer."
  (interactive "p")
  (compilation-next-error (- n)))

(defun geiser-repl-clear-buffer ()
  "Delete the output generated by the scheme process."
  (interactive)
  (let ((inhibit-read-only t))
    (delete-region (point-min) (geiser-repl--last-prompt-start))
    (when (< (point) (geiser-repl--last-prompt-end))
      (goto-char (geiser-repl--last-prompt-end)))
    (recenter t)))

(defvar geiser-repl-mode-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map comint-mode-map)

    (define-key map "\C-d" 'delete-char)
    (define-key map "\C-m" 'geiser-repl--maybe-send)
    (define-key map [return] 'geiser-repl--maybe-send)
    (define-key map "\C-j" 'geiser-repl--newline-and-indent)
    (define-key map (kbd "TAB") 'geiser-repl-tab-dwim)
    (define-key map [backtab] 'geiser-repl--previous-error)

    (define-key map "\C-a" 'geiser-repl--bol)
    (define-key map (kbd "<home>") 'geiser-repl--bol)

    (geiser-menu--defmenu repl map
      ("Complete symbol" ((kbd "M-TAB"))
       completion-at-point :enable (geiser--symbol-at-point))
      ("Complete module name" ((kbd "C-.") (kbd "M-`"))
       geiser-completion--complete-module :enable (geiser--symbol-at-point))
      ("Edit symbol" "\M-." geiser-edit-symbol-at-point
       :enable (geiser--symbol-at-point))
      --
      ("Load scheme file..." "\C-c\C-l" geiser-load-file)
      ("Switch to module..." "\C-c\C-m" switch-to-geiser-module)
      ("Import module..." "\C-c\C-i" geiser-repl-import-module)
      ("Add to load path..." "\C-c\C-r" geiser-add-to-load-path)
      --
      ("Previous matching input" "\M-p" comint-previous-matching-input-from-input
       "Previous input matching current")
      ("Next matching input" "\M-n" comint-next-matching-input-from-input
       "Next input matching current")
      ("Previous prompt" "\C-c\C-p" geiser-repl-previous-prompt)
      ("Next prompt" "\C-c\C-n" geiser-repl-next-prompt)
      ("Previous input" "\C-c\M-p" comint-previous-input)
      ("Next input" "\C-c\M-n" comint-next-input)
      --
      ("Interrupt evaluation" ("\C-c\C-k" "\C-c\C-c")
       geiser-repl-interrupt)
      --
      (mode "Autodoc mode" ("\C-c\C-da" "\C-c\C-d\C-a") geiser-autodoc-mode)
      ("Symbol documentation" ("\C-c\C-dd" "\C-c\C-d\C-d")
       geiser-doc-symbol-at-point
       "Documentation for symbol at point" :enable (geiser--symbol-at-point))
      ("Lookup symbol in manual" ("\C-c\C-di" "\C-c\C-d\C-i")
       geiser-doc-look-up-manual
       "Documentation for symbol at point" :enable (geiser--symbol-at-point))
      ("Module documentation" ("\C-c\C-dm" "\C-c\C-d\C-m") geiser-repl--doc-module
       "Documentation for module at point" :enable (geiser--symbol-at-point))
      --
      ("Clear buffer" "\C-c\M-o" geiser-repl-clear-buffer
       "Clean up REPL buffer, leaving just a lonely prompt")
      ("Toggle ()/[]" ("\C-c\C-e\C-[" "\C-c\C-e[") geiser-squarify)
      ("Insert λ" ("\C-c\\" "\C-c\C-\\") geiser-insert-lambda)
      --
      ("Kill Scheme interpreter" "\C-c\C-q" geiser-repl-exit
       :enable (geiser-repl--live-p))
      ("Restart" "\C-c\C-z" switch-to-geiser :enable (not (geiser-repl--live-p)))

      --
      (custom "REPL options" geiser-repl))

    (define-key map [menu-bar completion] 'undefined)
    map))

(define-derived-mode geiser-repl-mode comint-mode "REPL"
  "Major mode for interacting with an inferior scheme repl process.
\\{geiser-repl-mode-map}"
  (scheme-mode-variables)
  (set (make-local-variable 'geiser-repl--last-output-start) (point-marker))
  (set (make-local-variable 'geiser-repl--last-output-end) (point-marker))
  (set (make-local-variable 'face-remapping-alist)
       '((comint-highlight-prompt geiser-font-lock-repl-prompt)
         (comint-highlight-input geiser-font-lock-repl-input)))
  (set (make-local-variable 'mode-line-process) nil)
  (set (make-local-variable 'comint-use-prompt-regexp) nil)
  (set (make-local-variable 'comint-prompt-read-only)
       geiser-repl-read-only-prompt-p)
  (setq comint-process-echoes nil)
  (set (make-local-variable 'beginning-of-defun-function)
       'geiser-repl--beginning-of-defun)
  (set (make-local-variable 'comint-input-ignoredups)
       geiser-repl-history-no-dups-p)
  (setq geiser-eval--get-module-function 'geiser-repl--module-function)
  (geiser-completion--setup t)
  (setq geiser-smart-tab-mode-string "")
  (geiser-smart-tab-mode t)

  (setq-local font-lock-fontify-region-function
              #'geiser-repl--wrap-fontify-region-function)
  (setq-local font-lock-unfontify-region-function
              #'geiser-repl--wrap-unfontify-region-function)

  ;; enabling compilation-shell-minor-mode without the annoying highlighter
  (compilation-setup t))


;;; User commands

(defun run-geiser (impl)
  "Start a new Geiser REPL."
  (interactive
   (list (geiser-repl--get-impl "Start Geiser for scheme implementation: ")))
  (geiser-repl--start-repl impl nil))

(defalias 'geiser 'run-geiser)

(defun geiser-connect (impl &optional host port)
  "Start a new Geiser REPL connected to a remote Scheme process."
  (interactive
   (list (geiser-repl--get-impl "Connect to Scheme implementation: ")))
  (geiser-repl--start-repl impl (geiser-repl--read-address host port)))

(defun geiser-connect-local (impl socket)
  "Start a new Geiser REPL connected to a remote Scheme process
over a Unix-domain socket."
  (interactive
   (list (geiser-repl--get-impl "Connect to Scheme implementation: ")
         (expand-file-name (read-file-name "Socket file name: "))))
  (geiser-repl--start-repl impl socket))

(defvar-local geiser-repl--last-scm-buffer nil)

(defun geiser-repl--maybe-remember-scm-buffer (buffer)
  (when (and buffer
             (eq 'scheme-mode (with-current-buffer buffer major-mode))
             (eq major-mode 'geiser-repl-mode))
    (setq geiser-repl--last-scm-buffer buffer)))

(defvar-local geiser-repl--binary nil)

(defvar-local geiser-repl--arglist nil)

(defun geiser-repl--get-binary (impl)
  (or geiser-repl--binary (geiser-repl--binary impl)))

(defun geiser-repl--get-arglist (impl)
  (or geiser-repl--arglist (geiser-repl--arglist impl)))

(defun geiser-repl--call-in-repl (cmd)
  (when-let (b (geiser-repl--repl/impl geiser-impl--implementation))
    (save-window-excursion
      (with-current-buffer b (funcall cmd)))))

(defun switch-to-geiser (&optional ask impl buffer)
  "Switch to running Geiser REPL.

If REPL is the current buffer, switch to the previously used
scheme buffer.

With prefix argument, ask for which one if more than one is running.
If no REPL is running, execute `run-geiser' to start a fresh one."
  (interactive "P")
  (let* ((impl (or impl geiser-impl--implementation))
         (in-repl (eq major-mode 'geiser-repl-mode))
         (in-live-repl (and in-repl (get-buffer-process (current-buffer))))
         (repl (unless ask
                 (if impl
                     (geiser-repl--repl/impl impl)
                   (or geiser-repl--repl (car geiser-repl--repls))))))
    (cond (in-live-repl
           (when (and (not (eq repl buffer))
                      (buffer-live-p geiser-repl--last-scm-buffer))
             (geiser-repl--switch-to-buffer geiser-repl--last-scm-buffer)))
          (repl (geiser-repl--switch-to-buffer repl))
          ((geiser-repl--remote-p)
           (geiser-connect impl (geiser-repl--host) (geiser-repl--port)))
          ((geiser-repl--local-p)
           (geiser-connect-local impl geiser-repl--address))
          (impl (run-geiser impl))
          (t (call-interactively 'run-geiser)))
    (geiser-repl--maybe-remember-scm-buffer buffer)))

(defun switch-to-geiser-module (&optional module buffer)
  "Switch to running Geiser REPL and try to enter a given module."
  (interactive)
  (let* ((module (or module
                     (geiser-completion--read-module
                      "Switch to module (default top-level): ")))
         (cmd (and module
                   (geiser-repl--enter-cmd geiser-impl--implementation
                                           module))))
    (unless (eq major-mode 'geiser-repl-mode)
      (switch-to-geiser nil nil (or buffer (current-buffer))))
    (geiser-repl--send cmd)))

(defun geiser-repl-import-module (&optional module)
  "Import a given module in the current namespace of the REPL."
  (interactive)
  (let* ((module (or module
                     (geiser-completion--read-module "Import module: ")))
         (cmd (and module
                   (geiser-repl--import-cmd geiser-impl--implementation
                                            module))))
    (switch-to-geiser nil nil (current-buffer))
    (geiser-repl--send cmd)))

(defun geiser-repl-exit (&optional arg)
  "Exit the current REPL.
With a prefix argument, force exit by killing the scheme process."
  (interactive "P")
  (when (or (not geiser-repl-query-on-exit-p)
            (y-or-n-p "Really quit this REPL? "))
    (geiser-con--connection-deactivate geiser-repl--connection t)
    (let ((cmd (and (not arg)
                    (geiser-repl--exit-cmd geiser-impl--implementation))))
      (if cmd
          (when (stringp cmd) (geiser-repl--send cmd))
        (comint-kill-subjob)))))

(defun geiser-repl-next-prompt (n)
  (interactive "p")
  (when (> n 0)
    (end-of-line)
    (re-search-forward comint-prompt-regexp nil 'go n)))

(defun geiser-repl-previous-prompt (n)
  (interactive "p")
  (when (> n 0)
    (end-of-line 0)
    (when (re-search-backward comint-prompt-regexp nil 'go n)
      (goto-char (match-end 0)))))


;;; Unload:

(defun geiser-repl--repl-list ()
  (let (lst)
    (dolist (repl geiser-repl--repls lst)
      (when (buffer-live-p repl)
        (with-current-buffer repl
          (push (cons geiser-impl--implementation
                      geiser-repl--address)
                lst))))))

(defun geiser-repl--restore (impls)
  (dolist (impl impls)
    (when impl
      (condition-case err
          (geiser-repl--start-repl (car impl) (cdr impl))
        (error (message (error-message-string err)))))))

(defun geiser-repl-unload-function ()
  (dolist (repl geiser-repl--repls)
    (when (buffer-live-p repl)
      (with-current-buffer repl
        (let ((geiser-repl-query-on-exit-p nil)) (geiser-repl-exit))
        (sit-for 0.05)
        (kill-buffer)))))


(provide 'geiser-repl)


;;; Initialization:
;; After providing 'geiser-repl, so that impls can use us.
(mapc 'geiser-impl--load-impl geiser-active-implementations)