This repository has been archived by the owner on Mar 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
scion.el
2360 lines (2009 loc) · 82.6 KB
/
scion.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
;;; scion.el --- Haskell Minor Mode for Interacting with the Scion Library
;;
;;;; License
;; Copyright (C) 2003 Eric Marsden, Luke Gorrie, Helmut Eller
;; Copyright (C) 2004,2005,2006 Luke Gorrie, Helmut Eller
;; Copyright (C) 2008 Thomas Schilling
;;
;; 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 2 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, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
;; MA 02111-1307, USA.
;;;; Dependencies and setup
(eval-and-compile
(require 'cl)
(unless (fboundp 'define-minor-mode)
(require 'easy-mmode)
(defalias 'define-minor-mode 'easy-mmode-define-minor-mode)))
(require 'hideshow)
(eval-when (compile)
(require 'apropos)
(require 'outline)
(require 'ido)
;; (require 'etags)
)
;;;---------------------------------------------------------------------------
;;;; Customize groups
;;
;;;;; scion
(defgroup scion nil
"Interaction with the Scion Server."
:prefix "scion-"
:group 'applications)
;;;;; scion-ui
(defgroup scion-ui nil
"Interaction with the Scion Server."
:prefix "scion-"
:group 'scion)
(defcustom scion-kill-without-query-p nil
"If non-nil, kill SCION processes without query when quitting Emacs.
This applies to the *inferior-lisp* buffer and the network connections."
:type 'boolean
:group 'scion-ui)
;;;;; scion-haskell
(defgroup scion-haskell nil
"Haskell server configuration."
:prefix "scion-"
:group 'scion)
(defcustom scion-connected-hook nil
"List of functions to call when SCION connects to Haskell."
:type 'hook
:group 'scion-haskell)
(defcustom scion-haskell-host "127.0.0.1"
"The default hostname (or IP address) to connect to."
:type 'string
:group 'scion-haskell)
(defcustom scion-port 4005
"Port to use as the default for `scion-connect'."
:type 'integer
:group 'scion-haskell)
(make-variable-buffer-local
(defvar scion-modeline-string nil
"The string that should be displayed in the modeline if
`scion-extended-modeline' is true, and which indicates the
current connection, package and state of a Lisp buffer.
The string is periodically updated by an idle timer."))
;;;---------------------------------------------------------------------------
;;;; Macros
(defmacro* when-let ((var value) &rest body)
"Evaluate VALUE, and if the result is non-nil bind it to VAR and
evaluate BODY.
\(fn (VAR VALUE) &rest BODY)"
`(let ((,var ,value))
(when ,var ,@body)))
(defmacro destructure-case (value &rest patterns)
"Dispatch VALUE to one of PATTERNS.
A cross between `case' and `destructuring-bind'.
The pattern syntax is:
((HEAD . ARGS) . BODY)
The list of patterns is searched for a HEAD `eq' to the car of
VALUE. If one is found, the BODY is executed with ARGS bound to the
corresponding values in the CDR of VALUE."
(let ((operator (gensym "op-"))
(operands (gensym "rand-"))
(tmp (gensym "tmp-")))
`(let* ((,tmp ,value)
(,operator (car ,tmp))
(,operands (cdr ,tmp)))
(case ,operator
,@(mapcar (lambda (clause)
(if (eq (car clause) t)
`(t ,@(cdr clause))
(destructuring-bind ((op &rest rands) &rest body) clause
`(,op (destructuring-bind ,rands ,operands
. ,body)))))
patterns)
,@(if (eq (caar (last patterns)) t)
'()
`((t (error "Elisp destructure-case failed: %S" ,tmp))))))))
(put 'destructure-case 'lisp-indent-function 1)
;;;; Temporary Popup Buffers
;; Interface
(defmacro* scion-with-popup-buffer ((name &optional package
connection emacs-snapshot)
&body body)
"Similar to `with-output-to-temp-buffer'.
Bind standard-output and initialize some buffer-local variables.
Restore window configuration when closed.
NAME is the name of the buffer to be created.
PACKAGE is the value `scion-buffer-package'.
CONNECTION is the value for `scion-buffer-connection'.
If nil, no explicit connection is associated with
the buffer. If t, the current connection is taken.
If EMACS-SNAPSHOT is non-NIL, it's used to restore the previous
state of Emacs after closing the temporary buffer. Otherwise, the
current state will be saved and later restored."
`(let* ((vars% (list ,(if (eq package t) '(scion-current-package) package)
,(if (eq connection t) '(scion-connection) connection)
;; Defer the decision for NILness until runtime.
(or ,emacs-snapshot (scion-current-emacs-snapshot))))
(standard-output (scion-popup-buffer ,name vars%)))
(with-current-buffer standard-output
(prog1 (progn ,@body)
(assert (eq (current-buffer) standard-output))
(setq buffer-read-only t)
(scion-init-popup-buffer vars%)))))
(put 'scion-with-popup-buffer 'lisp-indent-function 1)
(defmacro* with-struct ((conc-name &rest slots) struct &body body)
"Like with-slots but works only for structs.
\(fn (CONC-NAME &rest SLOTS) STRUCT &body BODY)"
(flet ((reader (slot) (intern (concat (symbol-name conc-name)
(symbol-name slot)))))
(let ((struct-var (gensym "struct")))
`(let ((,struct-var ,struct))
(symbol-macrolet
,(mapcar (lambda (slot)
(etypecase slot
(symbol `(,slot (,(reader slot) ,struct-var)))
(cons `(,(first slot) (,(reader (second slot))
,struct-var)))))
slots)
. ,body)))))
(put 'with-struct 'lisp-indent-function 2)
(defmacro scion-define-keys (keymap &rest key-command)
"Define keys in KEYMAP. Each KEY-COMMAND is a list of (KEY COMMAND)."
`(progn . ,(mapcar (lambda (k-c) `(define-key ,keymap . ,k-c))
key-command)))
(put 'slime-define-keys 'lisp-indent-function 1)
;;;---------------------------------------------------------------------------
;;;;;; Tree View Widget
(defstruct (scion-tree (:conc-name scion-tree.))
item
(print-fn #'scion-tree-default-printer :type function)
(kids '() :type list)
(collapsed-p t :type boolean)
(prefix "" :type string)
(start-mark nil)
(end-mark nil)
(plist '() :type list))
(defun scion-tree-leaf-p (tree)
(not (scion-tree.kids tree)))
(defun scion-tree-default-printer (tree)
(princ (scion-tree.item tree) (current-buffer)))
(defun scion-tree-decoration (tree)
(cond ((scion-tree-leaf-p tree) "-- ")
((scion-tree.collapsed-p tree) "[+] ")
(t "-+ ")))
(defun scion-tree-insert-list (list prefix)
"Insert a list of trees."
(loop for (elt . rest) on list
do (cond (rest
(insert prefix " |")
(scion-tree-insert elt (concat prefix " |"))
(insert "\n"))
(t
(insert prefix " `")
(scion-tree-insert elt (concat prefix " "))))))
(defun scion-tree-insert-decoration (tree)
(insert (scion-tree-decoration tree)))
(defun scion-tree-indent-item (start end prefix)
"Insert PREFIX at the beginning of each but the first line.
This is used for labels spanning multiple lines."
(save-excursion
(goto-char end)
(beginning-of-line)
(while (< start (point))
(insert-before-markers prefix)
(forward-line -1))))
(defun scion-tree-insert (tree prefix)
"Insert TREE prefixed with PREFIX at point."
(with-struct (scion-tree. print-fn kids collapsed-p start-mark end-mark) tree
(let ((line-start (line-beginning-position)))
(setf start-mark (point-marker))
(scion-tree-insert-decoration tree)
(funcall print-fn tree)
(scion-tree-indent-item start-mark (point) (concat prefix " "))
(add-text-properties line-start (point) (list 'scion-tree tree))
(set-marker-insertion-type start-mark t)
(when (and kids (not collapsed-p))
(terpri (current-buffer))
(scion-tree-insert-list kids prefix))
(setf (scion-tree.prefix tree) prefix)
(setf end-mark (point-marker)))))
(defun scion-tree-at-point ()
(cond ((get-text-property (point) 'scion-tree))
(t (error "No tree at point"))))
(defun scion-tree-delete (tree)
"Delete the region for TREE."
(delete-region (scion-tree.start-mark tree)
(scion-tree.end-mark tree)))
(defun scion-tree-toggle (tree)
"Toggle the visibility of TREE's children."
(with-struct (scion-tree. collapsed-p start-mark end-mark prefix) tree
(setf collapsed-p (not collapsed-p))
(scion-tree-delete tree)
(insert-before-markers " ") ; move parent's end-mark
(backward-char 1)
(scion-tree-insert tree prefix)
(delete-char 1)
(goto-char start-mark)))
;;;---------------------------------------------------------------------------
(defvar scion-program "scion_emacs"
"Program name of the Scion server.")
(defvar scion-last-compilation-result nil
"The result of the most recently issued compilation.")
(make-variable-buffer-local
(defvar scion-mode-line " Scion"))
(define-minor-mode scion-mode
"\\<scion-mode-map>\
Scion: Smart Haskell mode.
\\{scion-mode-map}"
nil
scion-mode-line
;; Fake binding to coax `define-minor-mode' to create the keymap
'((" " 'self-insert-command))
(when scion-last-compilation-result
(scion-highlight-notes (scion-compiler-notes) (current-buffer))))
(define-key scion-mode-map " " 'self-insert-command)
;; dummy definitions for the compiler
(defvar scion-net-coding-system)
(defvar scion-net-processes)
(defvar scion-default-connection)
(defun scion (&optional command)
"Start a Scion server and connect to it."
(interactive)
(let ((server-program (or command scion-program)))
(scion-start :program server-program)))
(defun* scion-start (&key (program scion-program)
program-args
env
directory
name
(buffer "*scion-server*"))
(let ((proc (scion-maybe-start-server program program-args env
directory buffer)))
))
(defun scion-maybe-start-server (program program-args env directory buffer)
(cond
((not (comint-check-proc buffer))
(scion-start-server program program-args env directory buffer))
(t
(message "Scion server is already running")
nil)))
(defvar scion-connect-buffer nil
"Buffer that is currently trying to connect to a Scion server.")
(defun scion-start-server (program program-args env directory buffer)
(with-current-buffer (get-buffer-create buffer)
(when directory
(cd (expand-file-name directory)))
(delete-region (point-min) (point-max))
(comint-mode)
(setq scion-connect-buffer (current-buffer))
(message "Connecting... (Abort with `M-x scion-abort-connect`.)")
(add-hook 'comint-output-filter-functions
'scion-check-server-ready nil t)
(let ((process-environment (append env process-environment)))
(comint-exec (current-buffer) "scion-emacs" program nil program-args))
(let ((proc (get-buffer-process (current-buffer))))
; (scion-set-query-on-exit-flag proc)
proc)))
(defun scion-check-server-ready (server-output)
"Watches the server's output for the port number to connect to."
(let* ((regexp "^=== Listening on port: \\([0-9]+\\)$")
(port (save-excursion
(goto-char (point-min))
(when (re-search-forward regexp nil t)
(read (match-string 1)) ))))
(when port
(remove-hook 'comint-output-filter-functions
'scion-check-server-ready t)
(setq scion-connect-buffer nil)
(sleep-for 0.1) ;; give the server some time to get connected
(scion-connect "127.0.0.1" port))))
(defun scion-abort-connect ()
"Abort the current connection attempt."
(interactive)
(cond (scion-connect-buffer
(kill-buffer scion-connect-buffer)
(message "Connection attempt aborted."))
(t
(error "Not connecting."))))
(defun scion-connect (host port &optional coding-system)
"Connect to a running Swank server."
(interactive (list (read-from-minibuffer "Host: " scion-haskell-host)
(read-from-minibuffer "Port: " (format "%d" scion-port)
nil t)))
(when (and (interactive-p) scion-net-processes
(y-or-n-p "Close old connections first? "))
(scion-disconnect))
(message "Connecting to Scion Server on port %S.." port)
(let ((coding-system (or coding-system scion-net-coding-system)))
(scion-check-coding-system coding-system)
(message "Connecting to Scion Server on port %S.." port)
(let* ((process (scion-net-connect host port coding-system))
(scion-dispatching-connection process))
(scion-setup-connection process))))
;;;---------------------------------------------------------------------------
;;;; Networking
;;;---------------------------------------------------------------------------
;;;
;;; This section covers the low-level networking: establishing
;;; connections and encoding/decoding protocol messages.
;;;
;;; Each SCION protocol message begins with a 3-byte length header
;;; followed by an S-expression as text. [XXX: The sexp must be readable
;;; both by Emacs and by Common Haskell, so if it contains any embedded
;;; code fragments they should be sent as strings.]
;;;
;;; The set of meaningful protocol messages are not specified
;;; here. They are defined elsewhere by the event-dispatching
;;; functions in this file and in Scion/Server/Emacs.hs.
(defvar scion-net-processes nil
"List of processes (sockets) connected to Haskell.")
(defvar scion-net-process-close-hooks '()
"List of functions called when a scion network connection closes.
The functions are called with the process as their argument.")
(defun scion-secret ()
"Finds the magic secret from the user's home directory.
Returns nil if the file doesn't exist or is empty; otherwise the first
line of the file."
nil) ; disable for now
;;;---------------------------------------------------------------------------
;;; Interface
(defun scion-net-connect (host port coding-system)
"Establish a connection with a Scion Server.
<hostname> <port> <coding-system> -> <network-stream-process>"
(let* ((inhibit-quit nil)
(proc (open-network-stream "Scion Server" nil host port))
(buffer (scion-make-net-buffer " *scion-connection*")))
(push proc scion-net-processes)
(set-process-buffer proc buffer)
(set-process-filter proc 'scion-net-filter)
(set-process-sentinel proc 'scion-net-sentinel)
(scion-set-query-on-exit-flag proc)
(when (fboundp 'set-process-coding-system)
(scion-check-coding-system coding-system)
(set-process-coding-system proc coding-system coding-system))
(when-let (secret (scion-secret))
(scion-net-send secret proc))
proc))
(defun scion-make-net-buffer (name)
"Make a buffer suitable for a network process."
(let ((buffer (generate-new-buffer name)))
(with-current-buffer buffer
(buffer-disable-undo))
buffer))
(defun scion-set-query-on-exit-flag (process)
"Set PROCESS's query-on-exit-flag to `scion-kill-without-query-p'."
(when scion-kill-without-query-p
;; avoid byte-compiler warnings
(let ((fun (if (fboundp 'set-process-query-on-exit-flag)
'set-process-query-on-exit-flag
'process-kill-without-query)))
(funcall fun process nil))))
;;;---------------------------------------------------------------------------
;;;;; Coding system madness
(defvar scion-net-valid-coding-systems
'((iso-latin-1-unix nil "iso-latin-1-unix")
(iso-8859-1-unix nil "iso-latin-1-unix")
(binary nil "iso-latin-1-unix")
;; (utf-8-unix t "utf-8-unix")
;; (emacs-mule-unix t "emacs-mule-unix")
;; (euc-jp-unix t "euc-jp-unix")
)
"A list of valid coding systems.
Each element is of the form: (NAME MULTIBYTEP CL-NAME)")
(defun scion-find-coding-system (name)
"Return the coding system for the symbol NAME.
The result is either an element in `scion-net-valid-coding-systems'
or NIL."
(let* ((probe (assq name scion-net-valid-coding-systems)))
(if (and probe (if (fboundp 'check-coding-system)
(ignore-errors (check-coding-system (car probe)))
(eq (car probe) 'binary)))
probe)))
(defvar scion-net-coding-system
(find-if 'scion-find-coding-system
'(iso-latin-1-unix iso-8859-1-unix binary))
"*Coding system used for network connections.
See also `scion-net-valid-coding-systems'.")
(defun scion-check-coding-system (coding-system)
"Signal an error if CODING-SYSTEM isn't a valid coding system."
(interactive)
(let ((props (scion-find-coding-system coding-system)))
(unless props
(error "Invalid scion-net-coding-system: %s. %s"
coding-system (mapcar #'car scion-net-valid-coding-systems)))
(when (and (second props) (boundp 'default-enable-multibyte-characters))
(assert default-enable-multibyte-characters))
t))
(defcustom scion-repl-history-file-coding-system
(cond ((scion-find-coding-system 'utf-8-unix) 'utf-8-unix)
(t scion-net-coding-system))
"*The coding system for the history file."
:type 'symbol
:group 'scion-repl)
(defun scion-coding-system-mulibyte-p (coding-system)
(second (scion-find-coding-system coding-system)))
(defun scion-coding-system-cl-name (coding-system)
(third (scion-find-coding-system coding-system)))
;;;---------------------------------------------------------------------------
;;; Interface
(defun scion-net-send (sexp proc)
"Send a SEXP to Lisp over the socket PROC.
This is the lowest level of communication. The sexp will be READ and
EVAL'd by Lisp."
(let* ((msg (concat (scion-prin1-to-string sexp) "\n"))
(string (concat (scion-net-encode-length (length msg)) msg))
(coding-system (cdr (process-coding-system proc))))
(scion-log-event sexp)
(cond ((scion-safe-encoding-p coding-system string)
(process-send-string proc string))
(t (error "Coding system %s not suitable for %S"
coding-system string)))))
(defun scion-safe-encoding-p (coding-system string)
"Return true iff CODING-SYSTEM can safely encode STRING."
(if (featurep 'xemacs)
;; FIXME: XEmacs encodes non-encodeable chars as ?~ automatically
t
(or (let ((candidates (find-coding-systems-string string))
(base (coding-system-base coding-system)))
(or (equal candidates '(undecided))
(memq base candidates)))
(and (not (multibyte-string-p string))
(not (scion-coding-system-mulibyte-p coding-system))))))
(defun scion-net-close (process &optional debug)
(setq scion-net-processes (remove process scion-net-processes))
(when (eq process scion-default-connection)
(setq scion-default-connection nil))
(cond (debug
(set-process-sentinel process 'ignore)
(set-process-filter process 'ignore)
(delete-process process))
(t
(run-hook-with-args 'scion-net-process-close-hooks process)
;; killing the buffer also closes the socket
(kill-buffer (process-buffer process)))))
(defun scion-net-sentinel (process message)
(message "Connection to Scion server closed unexpectedly: %s" message)
(scion-net-close process))
;;; Socket input is handled by `scion-net-filter', which decodes any
;;; complete messages and hands them off to the event dispatcher.
(defun scion-net-filter (process string)
"Accept output from the socket and process all complete messages."
(with-current-buffer (process-buffer process)
(goto-char (point-max))
(insert string))
(scion-process-available-input process))
(defun scion-process-available-input (process)
"Process all complete messages that have arrived from Lisp."
(with-current-buffer (process-buffer process)
(while (scion-net-have-input-p)
(let ((event (scion-net-read-or-lose process))
(ok nil))
(scion-log-event event)
(unwind-protect
(save-current-buffer
(scion-dispatch-event event process)
(setq ok t))
(unless ok
(scion-run-when-idle 'scion-process-available-input process)))))))
(defun scion-net-have-input-p ()
"Return true if a complete message is available."
(goto-char (point-min))
(and (>= (buffer-size) 6)
(>= (- (buffer-size) 6) (scion-net-decode-length))))
(defun scion-run-when-idle (function &rest args)
"Call FUNCTION as soon as Emacs is idle."
(apply #'run-at-time
(if (featurep 'xemacs) itimer-short-interval 0)
nil function args))
(defun scion-net-read-or-lose (process)
(condition-case error
(scion-net-read)
(error
(debug)
(scion-net-close process t)
(error "net-read error: %S" error))))
(defun scion-net-read ()
"Read a message from the network buffer."
(goto-char (point-min))
(let* ((length (scion-net-decode-length))
(start (+ 6 (point)))
(end (+ start length)))
(assert (plusp length))
(prog1 (save-restriction
(narrow-to-region start end)
(read (current-buffer)))
(delete-region (point-min) end))))
(defun scion-net-decode-length ()
"Read a 24-bit hex-encoded integer from buffer."
(string-to-number (buffer-substring-no-properties (point) (+ (point) 6)) 16))
(defun scion-net-encode-length (n)
"Encode an integer into a 24-bit hex string."
(format "%06x" n))
(defun scion-prin1-to-string (sexp)
"Like `prin1-to-string' but don't octal-escape non-ascii characters.
This is more compatible with the CL reader."
(with-temp-buffer
(let (print-escape-nonascii
print-escape-newlines
print-length
print-level)
(prin1 sexp (current-buffer))
(buffer-string))))
;;;---------------------------------------------------------------------------
;;;; Connections
;;;
;;; "Connections" are the high-level Emacs<->Lisp networking concept.
;;;
;;; Emacs has a connection to each Lisp process that it's interacting
;;; with. Typically there would only be one, but a user can choose to
;;; connect to many Lisps simultaneously.
;;;
;;; A connection consists of a control socket, optionally an extra
;;; socket dedicated to receiving Lisp output (an optimization), and a
;;; set of connection-local state variables.
;;;
;;; The state variables are stored as buffer-local variables in the
;;; control socket's process-buffer and are used via accessor
;;; functions. These variables include things like the *FEATURES* list
;;; and Unix Pid of the Lisp process.
;;;
;;; One connection is "current" at any given time. This is:
;;; `scion-dispatching-connection' if dynamically bound, or
;;; `scion-buffer-connection' if this is set buffer-local, or
;;; `scion-default-connection' otherwise.
;;;
;;; When you're invoking commands in your source files you'll be using
;;; `scion-default-connection'. This connection can be interactively
;;; reassigned via the connection-list buffer.
;;;
;;; When a command creates a new buffer it will set
;;; `scion-buffer-connection' so that commands in the new buffer will
;;; use the connection that the buffer originated from. For example,
;;; the apropos command creates the *Apropos* buffer and any command
;;; in that buffer (e.g. `M-.') will go to the same Lisp that did the
;;; apropos search. REPL buffers are similarly tied to their
;;; respective connections.
;;;
;;; When Emacs is dispatching some network message that arrived from a
;;; connection it will dynamically bind `scion-dispatching-connection'
;;; so that the event will be processed in the context of that
;;; connection.
;;;
;;; This is mostly transparent. The user should be aware that he can
;;; set the default connection to pick which Lisp handles commands in
;;; Lisp-mode source buffers, and scion hackers should be aware that
;;; they can tie a buffer to a specific connection. The rest takes
;;; care of itself.
(defvar scion-dispatching-connection nil
"Network process currently executing.
This is dynamically bound while handling messages from Lisp; it
overrides `scion-buffer-connection' and `scion-default-connection'.")
(make-variable-buffer-local
(defvar scion-buffer-connection nil
"Network connection to use in the current buffer.
This overrides `scion-default-connection'."))
(defvar scion-default-connection nil
"Network connection to use by default.
Used for all Lisp communication, except when overridden by
`scion-dispatching-connection' or `scion-buffer-connection'.")
(defun scion-current-connection ()
"Return the connection to use for Lisp interaction.
Return nil if there's no connection."
(or scion-dispatching-connection
scion-buffer-connection
scion-default-connection))
(defun scion-connection ()
"Return the connection to use for Lisp interaction.
Signal an error if there's no connection."
(let ((conn (scion-current-connection)))
(cond ((and (not conn) scion-net-processes)
(or (scion-auto-select-connection)
(error "No default connection selected.")))
((not conn)
(or (scion-auto-connect)
(error "Not connected.")))
((not (eq (process-status conn) 'open))
(error "Connection closed."))
(t conn))))
(defvar scion-auto-connect 'always)
(defun scion-auto-connect ()
(cond ((or (eq scion-auto-connect 'always)
(and (eq scion-auto-connect 'ask)
(y-or-n-p "No connection. Start Scion? ")))
(save-window-excursion
(scion) ; XXX
(while (not (scion-current-connection))
(sleep-for 1))
(scion-connection)))
(t nil)))
(defvar scion-auto-select-connection 'ask)
(defun scion-auto-select-connection ()
(let* ((c0 (car scion-net-processes))
(c (cond ((eq scion-auto-select-connection 'always) c0)
((and (eq scion-auto-select-connection 'ask)
(y-or-n-p
(format "No default connection selected. %s %s? "
"Switch to" (scion-connection-name c0))))
c0))))
(when c
(scion-select-connection c)
(message "Switching to connection: %s" (scion-connection-name c))
c)))
(defun scion-select-connection (process)
"Make PROCESS the default connection."
(setq scion-default-connection process))
(defun scion-cycle-connections ()
"Change current scion connection, and make it buffer local."
(interactive)
(let* ((tail (or (cdr (member (scion-current-connection)
scion-net-processes))
scion-net-processes))
(p (car tail)))
(scion-select-connection p)
(unless (eq major-mode 'scion-repl-mode)
(setq scion-buffer-connection p))
(message "Lisp: %s %s" (scion-connection-name p) (process-contact p))))
(defmacro* scion-with-connection-buffer ((&optional process) &rest body)
"Execute BODY in the process-buffer of PROCESS.
If PROCESS is not specified, `scion-connection' is used.
\(fn (&optional PROCESS) &body BODY))"
`(with-current-buffer
(process-buffer (or ,process (scion-connection)
(error "No connection")))
,@body))
(put 'scion-with-connection-buffer 'lisp-indent-function 1)
(defun scion-connected-p ()
"Return true if the Swank connection is open."
(not (null scion-net-processes)))
(defun scion-compute-connection-state (conn)
(cond ((null conn) :disconnected)
;((scion-stale-connection-p conn) :stale)
;((scion-debugged-connection-p conn) :debugged)
((and (scion-use-sigint-for-interrupt conn)
(scion-busy-p conn)) :busy)
((eq scion-buffer-connection conn) :local)
(t :connected)))
(defun scion-connection-state-as-string (state)
(case state
(:connected "")
(:disconnected "not connected")
(:busy "busy..")
(:debugged "debugged..")
(:stale "stale")
(:local "local")
))
;;; Connection-local variables:
(defmacro scion-def-connection-var (varname &rest initial-value-and-doc)
"Define a connection-local variable.
The value of the variable can be read by calling the function of the
same name (it must not be accessed directly). The accessor function is
setf-able.
The actual variable bindings are stored buffer-local in the
process-buffers of connections. The accessor function refers to
the binding for `scion-connection'."
(let ((real-var (intern (format "%s:connlocal" varname))))
`(progn
;; Variable
(make-variable-buffer-local
(defvar ,real-var ,@initial-value-and-doc))
;; Accessor
(defun ,varname (&optional process)
(scion-with-connection-buffer (process) ,real-var))
;; Setf
(defsetf ,varname (&optional process) (store)
`(scion-with-connection-buffer (,process)
(setq (\, (quote (\, real-var))) (\, store))
(\, store)))
'(\, varname))))
(put 'scion-def-connection-var 'lisp-indent-function 2)
;; Let's indulge in some pretty colours.
(unless (featurep 'xemacs)
(font-lock-add-keywords
'emacs-lisp-mode
'(("(\\(scion-def-connection-var\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"
(1 font-lock-keyword-face)
(2 font-lock-variable-name-face)))))
(scion-def-connection-var scion-connection-number nil
"Serial number of a connection.
Bound in the connection's process-buffer.")
(scion-def-connection-var scion-pid nil
"The process id of the Haskell process.")
(scion-def-connection-var scion-connection-name nil
"The short name for connection.")
;;;;; Connection setup
(defvar scion-connection-counter 0
"The number of SCION connections made. For generating serial numbers.")
;;; Interface
(defun scion-setup-connection (process)
"Make a connection out of PROCESS."
(let ((scion-dispatching-connection process))
(scion-init-connection-state process)
(scion-select-connection process)
process))
(defun scion-init-connection-state (proc)
"Initialize connection state in the process-buffer of PROC."
;; To make life simpler for the user: if this is the only open
;; connection then reset the connection counter.
(when (equal scion-net-processes (list proc))
(setq scion-connection-counter 0))
(scion-with-connection-buffer ()
(setq scion-buffer-connection proc))
(setf (scion-connection-number proc) (incf scion-connection-counter))
;; We do the rest of our initialization asynchronously. The current
;; function may be called from a timer, and if we setup the REPL
;; from a timer then it mysteriously uses the wrong keymap for the
;; first command.
(scion-eval-async '(connection-info)
(scion-curry #'scion-set-connection-info proc)))
(defun scion-set-connection-info (connection info)
"Initialize CONNECTION with INFO received from Lisp."
(let ((scion-dispatching-connection connection))
(destructuring-bind (&key pid version
&allow-other-keys) info
(scion-check-version version connection)
(setf (scion-pid) pid
(scion-connection-name) (format "%d" pid)))
(let ((args nil))
(run-hooks 'scion-connected-hook))
(message "Connected.")))
(defvar scion-protocol-version 1)
(defun scion-check-version (version conn)
(or (equal version scion-protocol-version)
(equal scion-protocol-version 'ignore)
(y-or-n-p
(format "Versions differ: %s (scion client) vs. %s (scion server). Continue? "
scion-protocol-version version))
(scion-net-close conn)
(top-level)))
(defun scion-generate-connection-name (lisp-name)
(loop for i from 1
for name = lisp-name then (format "%s<%d>" lisp-name i)
while (find name scion-net-processes
:key #'scion-connection-name :test #'equal)
finally (return name)))
(defun scion-connection-close-hook (process)
(when (eq process scion-default-connection)
(when scion-net-processes
(scion-select-connection (car scion-net-processes))
(message "Default connection closed; switched to #%S (%S)"
(scion-connection-number)
(scion-connection-name)))))
(add-hook 'scion-net-process-close-hooks 'scion-connection-close-hook)
;;;;; Commands on connections
(defun scion-disconnect ()
"Disconnect all connections."
(interactive)
(mapc #'scion-net-close scion-net-processes))
(defun scion-connection-port (connection)
"Return the remote port number of CONNECTION."
(if (featurep 'xemacs)
(car (process-id connection))
(cadr (process-contact connection))))
(defun scion-process (&optional connection)
"Return the Lisp process for CONNECTION (default `scion-connection').
Can return nil if there's no process object for the connection."
nil
;; (let ((proc (scion-inferior-process connection)))
;; (if (and proc
;; (memq (process-status proc) '(run stop)))
;; proc))
)
;; Non-macro version to keep the file byte-compilable.
;; (defun scion-set-inferior-process (connection process)
;; (setf (scion-inferior-process connection) process))
(defvar scion-inhibit-pipelining t
"*If true, don't send background requests if Lisp is already busy.")
(defun scion-background-activities-enabled-p ()
nil)
;;;; Communication protocol
;;;;; Emacs Lisp programming interface
;;;
;;; The programming interface for writing Emacs commands is based on
;;; remote procedure calls (RPCs). The basic operation is to ask Lisp
;;; to apply a named Lisp function to some arguments, then to do
;;; something with the result.
;;;
;;; Requests can be either synchronous (blocking) or asynchronous
;;; (with the result passed to a callback/continuation function). If
;;; an error occurs during the request then the debugger is entered
;;; before the result arrives -- for synchronous evaluations this
;;; requires a recursive edit.
;;;
;;; You should use asynchronous evaluations (`scion-eval-async') for
;;; most things. Reserve synchronous evaluations (`scion-eval') for
;;; the cases where blocking Emacs is really appropriate (like
;;; completion) and that shouldn't trigger errors (e.g. not evaluate
;;; user-entered code).
;;;
;;; We have the concept of the "current Lisp package". RPC requests
;;; always say what package the user is making them from and the Lisp
;;; side binds that package to *BUFFER-PACKAGE* to use as it sees
;;; fit. The current package is defined as the buffer-local value of
;;; `scion-buffer-package' if set, and otherwise the package named by
;;; the nearest IN-PACKAGE as found by text search (first backwards,
;;; then forwards).
;;;
;;; Similarly we have the concept of the current thread, i.e. which
;;; thread in the Lisp process should handle the request. The current
;;; thread is determined solely by the buffer-local value of
;;; `scion-current-thread'. This is usually bound to t meaning "no
;;; particular thread", but can also be used to nominate a specific
;;; thread. The REPL and the debugger both use this feature to deal
;;; with specific threads.
(make-variable-buffer-local
(defvar scion-current-thread t
"The id of the current thread on the Lisp side.
t means the \"current\" thread;
:repl-thread the thread that executes REPL requests;
fixnum a specific thread."))
(make-variable-buffer-local
(defvar scion-buffer-package nil
"The Lisp package associated with the current buffer.
This is set only in buffers bound to specific packages."))
(defun scion-current-package ()
nil)
(defvar scion-accept-process-output-supports-floats
(ignore-errors (accept-process-output nil 0.0) t))
(defun scion-accept-process-output (&optional process timeout)
"Like `accept-process-output' but the TIMEOUT argument can be a float."
(cond (scion-accept-process-output-supports-floats
(accept-process-output process timeout))
(t
(accept-process-output process