/[slime]/slime/swank.lisp
ViewVC logotype

Contents of /slime/swank.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.552 - (show annotations)
Tue Aug 5 17:38:53 2008 UTC (5 years, 8 months ago) by heller
Branch: MAIN
Changes since 1.551: +4 -3 lines
* swank.lisp (encode-message): Inhibit interrupts
while writing the length and the body.
1 ;;; -*- outline-regexp:";;;;;*" indent-tabs-mode:nil coding:latin-1-unix -*-
2 ;;;
3 ;;; This code has been placed in the Public Domain. All warranties
4 ;;; are disclaimed.
5 ;;;
6 ;;;; swank.lisp
7 ;;;
8 ;;; This file defines the "Swank" TCP server for Emacs to talk to. The
9 ;;; code in this file is purely portable Common Lisp. We do require a
10 ;;; smattering of non-portable functions in order to write the server,
11 ;;; so we have defined them in `swank-backend.lisp' and implemented
12 ;;; them separately for each Lisp implementation. These extensions are
13 ;;; available to us here via the `SWANK-BACKEND' package.
14
15 (defpackage :swank
16 (:use :cl :swank-backend)
17 (:export #:startup-multiprocessing
18 #:start-server
19 #:create-server
20 #:stop-server
21 #:restart-server
22 #:ed-in-emacs
23 #:inspect-in-emacs
24 #:print-indentation-lossage
25 #:swank-debugger-hook
26 #:emacs-inspect
27 ;;#:inspect-slot-for-emacs
28 ;; These are user-configurable variables:
29 #:*communication-style*
30 #:*dont-close*
31 #:*log-events*
32 #:*log-output*
33 #:*use-dedicated-output-stream*
34 #:*dedicated-output-stream-port*
35 #:*configure-emacs-indentation*
36 #:*readtable-alist*
37 #:*globally-redirect-io*
38 #:*global-debugger*
39 #:*sldb-printer-bindings*
40 #:*swank-pprint-bindings*
41 #:*default-worker-thread-bindings*
42 #:*macroexpand-printer-bindings*
43 #:*record-repl-results*
44 #:*debug-on-swank-error*
45 ;; These are re-exported directly from the backend:
46 #:buffer-first-change
47 #:frame-source-location-for-emacs
48 #:restart-frame
49 #:sldb-step
50 #:sldb-break
51 #:sldb-break-on-return
52 #:profiled-functions
53 #:profile-report
54 #:profile-reset
55 #:unprofile-all
56 #:profile-package
57 #:default-directory
58 #:set-default-directory
59 #:quit-lisp
60 #:with-swank-compilation-unit))
61
62 (in-package :swank)
63
64
65 ;;;; Top-level variables, constants, macros
66
67 (defconstant cl-package (find-package :cl)
68 "The COMMON-LISP package.")
69
70 (defconstant keyword-package (find-package :keyword)
71 "The KEYWORD package.")
72
73 (defvar *canonical-package-nicknames*
74 `((:common-lisp-user . :cl-user))
75 "Canonical package names to use instead of shortest name/nickname.")
76
77 (defvar *auto-abbreviate-dotted-packages* t
78 "Abbreviate dotted package names to their last component if T.")
79
80 (defvar *swank-io-package*
81 (let ((package (make-package :swank-io-package :use '())))
82 (import '(nil t quote) package)
83 package))
84
85 (defconstant default-server-port 4005
86 "The default TCP port for the server (when started manually).")
87
88 (defvar *swank-debug-p* t
89 "When true, print extra debugging information.")
90
91 (defvar *redirect-io* t
92 "When non-nil redirect Lisp standard I/O to Emacs.
93 Redirection is done while Lisp is processing a request for Emacs.")
94
95 (defvar *sldb-printer-bindings*
96 `((*print-pretty* . t)
97 (*print-level* . 4)
98 (*print-length* . 10)
99 (*print-circle* . t)
100 (*print-readably* . nil)
101 (*print-pprint-dispatch* . ,(copy-pprint-dispatch nil))
102 (*print-gensym* . t)
103 (*print-base* . 10)
104 (*print-radix* . nil)
105 (*print-array* . t)
106 (*print-lines* . 10)
107 (*print-escape* . t)
108 (*print-right-margin* . 65))
109 "A set of printer variables used in the debugger.")
110
111 (defvar *backtrace-printer-bindings*
112 `((*print-pretty* . nil)
113 (*print-level* . 4)
114 (*print-length* . 6))
115 "Pretter settings for printing backtraces.")
116
117 (defvar *default-worker-thread-bindings* '()
118 "An alist to initialize dynamic variables in worker threads.
119 The list has the form ((VAR . VALUE) ...). Each variable VAR will be
120 bound to the corresponding VALUE.")
121
122 (defun call-with-bindings (alist fun)
123 "Call FUN with variables bound according to ALIST.
124 ALIST is a list of the form ((VAR . VAL) ...)."
125 (let* ((rlist (reverse alist))
126 (vars (mapcar #'car rlist))
127 (vals (mapcar #'cdr rlist)))
128 (progv vars vals
129 (funcall fun))))
130
131 (defmacro with-bindings (alist &body body)
132 "See `call-with-bindings'."
133 `(call-with-bindings ,alist (lambda () ,@body)))
134
135 ;;; The `DEFSLIMEFUN' macro defines a function that Emacs can call via
136 ;;; RPC.
137
138 (defmacro defslimefun (name arglist &body rest)
139 "A DEFUN for functions that Emacs can call by RPC."
140 `(progn
141 (defun ,name ,arglist ,@rest)
142 ;; see <http://www.franz.com/support/documentation/6.2/doc/pages/variables/compiler/s_cltl1-compile-file-toplevel-compatibility-p_s.htm>
143 (eval-when (:compile-toplevel :load-toplevel :execute)
144 (export ',name :swank))))
145
146 (defun missing-arg ()
147 "A function that the compiler knows will never to return a value.
148 You can use (MISSING-ARG) as the initform for defstruct slots that
149 must always be supplied. This way the :TYPE slot option need not
150 include some arbitrary initial value like NIL."
151 (error "A required &KEY or &OPTIONAL argument was not supplied."))
152
153
154 ;;;; Hooks
155 ;;;
156 ;;; We use Emacs-like `add-hook' and `run-hook' utilities to support
157 ;;; simple indirection. The interface is more CLish than the Emacs
158 ;;; Lisp one.
159
160 (defmacro add-hook (place function)
161 "Add FUNCTION to the list of values on PLACE."
162 `(pushnew ,function ,place))
163
164 (defun run-hook (functions &rest arguments)
165 "Call each of FUNCTIONS with ARGUMENTS."
166 (dolist (function functions)
167 (apply function arguments)))
168
169 (defvar *new-connection-hook* '()
170 "This hook is run each time a connection is established.
171 The connection structure is given as the argument.
172 Backend code should treat the connection structure as opaque.")
173
174 (defvar *connection-closed-hook* '()
175 "This hook is run when a connection is closed.
176 The connection as passed as an argument.
177 Backend code should treat the connection structure as opaque.")
178
179 (defvar *pre-reply-hook* '()
180 "Hook run (without arguments) immediately before replying to an RPC.")
181
182 (defvar *after-init-hook* '()
183 "Hook run after user init files are loaded.")
184
185
186 ;;;; Connections
187 ;;;
188 ;;; Connection structures represent the network connections between
189 ;;; Emacs and Lisp. Each has a socket stream, a set of user I/O
190 ;;; streams that redirect to Emacs, and optionally a second socket
191 ;;; used solely to pipe user-output to Emacs (an optimization).
192 ;;;
193
194 (defstruct (connection
195 (:conc-name connection.)
196 (:print-function print-connection))
197 ;; Raw I/O stream of socket connection.
198 (socket-io (missing-arg) :type stream :read-only t)
199 ;; Optional dedicated output socket (backending `user-output' slot).
200 ;; Has a slot so that it can be closed with the connection.
201 (dedicated-output nil :type (or stream null))
202 ;; Streams that can be used for user interaction, with requests
203 ;; redirected to Emacs.
204 (user-input nil :type (or stream null))
205 (user-output nil :type (or stream null))
206 (user-io nil :type (or stream null))
207 ;; A stream that we use for *trace-output*; if nil, we user user-output.
208 (trace-output nil :type (or stream null))
209 ;; A stream where we send REPL results.
210 (repl-results nil :type (or stream null))
211 ;; In multithreaded systems we delegate certain tasks to specific
212 ;; threads. The `reader-thread' is responsible for reading network
213 ;; requests from Emacs and sending them to the `control-thread'; the
214 ;; `control-thread' is responsible for dispatching requests to the
215 ;; threads that should handle them; the `repl-thread' is the one
216 ;; that evaluates REPL expressions. The control thread dispatches
217 ;; all REPL evaluations to the REPL thread and for other requests it
218 ;; spawns new threads.
219 reader-thread
220 control-thread
221 repl-thread
222 ;; Callback functions:
223 ;; (SERVE-REQUESTS <this-connection>) serves all pending requests
224 ;; from Emacs.
225 (serve-requests (missing-arg) :type function)
226 ;; (READ) is called to read and return one message from Emacs.
227 (read (missing-arg) :type function)
228 ;; (SEND OBJECT) is called to send one message to Emacs.
229 (send (missing-arg) :type function)
230 ;; (CLEANUP <this-connection>) is called when the connection is
231 ;; closed.
232 (cleanup nil :type (or null function))
233 ;; Cache of macro-indentation information that has been sent to Emacs.
234 ;; This is used for preparing deltas to update Emacs's knowledge.
235 ;; Maps: symbol -> indentation-specification
236 (indentation-cache (make-hash-table :test 'eq) :type hash-table)
237 ;; The list of packages represented in the cache:
238 (indentation-cache-packages '())
239 ;; The communication style used.
240 (communication-style nil :type (member nil :spawn :sigio :fd-handler))
241 ;; The coding system for network streams.
242 (coding-system ))
243
244 (defun print-connection (conn stream depth)
245 (declare (ignore depth))
246 (print-unreadable-object (conn stream :type t :identity t)))
247
248 (defvar *connections* '()
249 "List of all active connections, with the most recent at the front.")
250
251 (defvar *emacs-connection* nil
252 "The connection to Emacs currently in use.")
253
254 (defvar *swank-state-stack* '()
255 "A list of symbols describing the current state. Used for debugging
256 and to detect situations where interrupts can be ignored.")
257
258 (defun default-connection ()
259 "Return the 'default' Emacs connection.
260 This connection can be used to talk with Emacs when no specific
261 connection is in use, i.e. *EMACS-CONNECTION* is NIL.
262
263 The default connection is defined (quite arbitrarily) as the most
264 recently established one."
265 (first *connections*))
266
267 (defslimefun state-stack ()
268 "Return the value of *SWANK-STATE-STACK*."
269 *swank-state-stack*)
270
271 ;; A conditions to include backtrace information
272 (define-condition swank-error (error)
273 ((condition :initarg :condition :reader swank-error.condition)
274 (backtrace :initarg :backtrace :reader swank-error.backtrace))
275 (:report (lambda (condition stream)
276 (princ (swank-error.condition condition) stream))))
277
278 (defun make-swank-error (condition)
279 (let ((bt (ignore-errors
280 (call-with-debugging-environment
281 (lambda () (backtrace 0 nil))))))
282 (make-condition 'swank-error :condition condition :backtrace bt)))
283
284 (add-hook *new-connection-hook* 'notify-backend-of-connection)
285 (defun notify-backend-of-connection (connection)
286 (declare (ignore connection))
287 (emacs-connected))
288
289
290 ;;;; Utilities
291
292 ;;;;; Helper macros
293
294 (defmacro with-io-redirection ((connection) &body body)
295 "Execute BODY I/O redirection to CONNECTION.
296 If *REDIRECT-IO* is true then all standard I/O streams are redirected."
297 `(maybe-call-with-io-redirection ,connection (lambda () ,@body)))
298
299 (defun maybe-call-with-io-redirection (connection fun)
300 (if *redirect-io*
301 (call-with-redirected-io connection fun)
302 (funcall fun)))
303
304 (defmacro with-connection ((connection) &body body)
305 "Execute BODY in the context of CONNECTION."
306 `(call-with-connection ,connection (lambda () ,@body)))
307
308 (defun call-with-connection (connection fun)
309 (let ((*emacs-connection* connection))
310 (with-io-redirection (*emacs-connection*)
311 (call-with-debugger-hook #'swank-debugger-hook fun))))
312
313 (defmacro without-interrupts (&body body)
314 `(call-without-interrupts (lambda () ,@body)))
315
316 (defmacro destructure-case (value &rest patterns)
317 "Dispatch VALUE to one of PATTERNS.
318 A cross between `case' and `destructuring-bind'.
319 The pattern syntax is:
320 ((HEAD . ARGS) . BODY)
321 The list of patterns is searched for a HEAD `eq' to the car of
322 VALUE. If one is found, the BODY is executed with ARGS bound to the
323 corresponding values in the CDR of VALUE."
324 (let ((operator (gensym "op-"))
325 (operands (gensym "rand-"))
326 (tmp (gensym "tmp-")))
327 `(let* ((,tmp ,value)
328 (,operator (car ,tmp))
329 (,operands (cdr ,tmp)))
330 (case ,operator
331 ,@(loop for (pattern . body) in patterns collect
332 (if (eq pattern t)
333 `(t ,@body)
334 (destructuring-bind (op &rest rands) pattern
335 `(,op (destructuring-bind ,rands ,operands
336 ,@body)))))
337 ,@(if (eq (caar (last patterns)) t)
338 '()
339 `((t (error "destructure-case failed: ~S" ,tmp))))))))
340
341 (defmacro with-temp-package (var &body body)
342 "Execute BODY with VAR bound to a temporary package.
343 The package is deleted before returning."
344 `(let ((,var (make-package (gensym "TEMP-PACKAGE-"))))
345 (unwind-protect (progn ,@body)
346 (delete-package ,var))))
347
348 (defmacro do-symbols* ((var &optional (package '*package*) result-form) &body body)
349 "Just like do-symbols, but makes sure a symbol is visited only once."
350 (let ((seen-ht (gensym "SEEN-HT")))
351 `(let ((,seen-ht (make-hash-table :test #'eq)))
352 (do-symbols (,var ,package ,result-form)
353 (unless (gethash ,var ,seen-ht)
354 (setf (gethash ,var ,seen-ht) t)
355 ,@body)))))
356
357
358 ;;;;; Logging
359
360 (defvar *log-events* nil)
361 (defvar *log-output*
362 (labels ((ref (x)
363 (cond ((typep x 'synonym-stream)
364 (ref (symbol-value (synonym-stream-symbol x))))
365 (t x))))
366 (ref *error-output*)))
367 (defvar *event-history* (make-array 40 :initial-element nil)
368 "A ring buffer to record events for better error messages.")
369 (defvar *event-history-index* 0)
370 (defvar *enable-event-history* t)
371
372 (defun log-event (format-string &rest args)
373 "Write a message to *terminal-io* when *log-events* is non-nil.
374 Useful for low level debugging."
375 (with-standard-io-syntax
376 (let ((*print-readably* nil)
377 (*print-pretty* nil)
378 (*package* *swank-io-package*))
379 (when *enable-event-history*
380 (setf (aref *event-history* *event-history-index*)
381 (format nil "~?" format-string args))
382 (setf *event-history-index*
383 (mod (1+ *event-history-index*) (length *event-history*))))
384 (when *log-events*
385 (write-string (escape-non-ascii (format nil "~?" format-string args))
386 *log-output*)
387 (force-output *log-output*)))))
388
389 (defun event-history-to-list ()
390 "Return the list of events (older events first)."
391 (let ((arr *event-history*)
392 (idx *event-history-index*))
393 (concatenate 'list (subseq arr idx) (subseq arr 0 idx))))
394
395 (defun dump-event-history (stream)
396 (dolist (e (event-history-to-list))
397 (dump-event e stream)))
398
399 (defun dump-event (event stream)
400 (cond ((stringp event)
401 (write-string (escape-non-ascii event) stream))
402 ((null event))
403 (t
404 (write-string
405 (escape-non-ascii (format nil "Unexpected event: ~A~%" event))
406 stream))))
407
408 (defun escape-non-ascii (string)
409 "Return a string like STRING but with non-ascii chars escaped."
410 (cond ((ascii-string-p string) string)
411 (t (with-output-to-string (out)
412 (loop for c across string do
413 (cond ((ascii-char-p c) (write-char c out))
414 (t (format out "\\x~4,'0X" (char-code c)))))))))
415
416 (defun ascii-string-p (o)
417 (and (stringp o)
418 (every #'ascii-char-p o)))
419
420 (defun ascii-char-p (c)
421 (<= (char-code c) 127))
422
423
424 ;;;;; Symbols
425
426 (defun symbol-status (symbol &optional (package (symbol-package symbol)))
427 "Returns one of
428
429 :INTERNAL if the symbol is _present_ in PACKAGE as an _internal_ symbol,
430
431 :EXTERNAL if the symbol is _present_ in PACKAGE as an _external_ symbol,
432
433 :INHERITED if the symbol is _inherited_ by PACKAGE through USE-PACKAGE,
434 but is not _present_ in PACKAGE,
435
436 or NIL if SYMBOL is not _accessible_ in PACKAGE.
437
438
439 Be aware not to get confused with :INTERNAL and how \"internal
440 symbols\" are defined in the spec; there is a slight mismatch of
441 definition with the Spec and what's commonly meant when talking
442 about internal symbols most times. As the spec says:
443
444 In a package P, a symbol S is
445
446 _accessible_ if S is either _present_ in P itself or was
447 inherited from another package Q (which implies
448 that S is _external_ in Q.)
449
450 You can check that with: (AND (SYMBOL-STATUS S P) T)
451
452
453 _present_ if either P is the /home package/ of S or S has been
454 imported into P or exported from P by IMPORT, or
455 EXPORT respectively.
456
457 Or more simply, if S is not _inherited_.
458
459 You can check that with: (LET ((STATUS (SYMBOL-STATUS S P)))
460 (AND STATUS
461 (NOT (EQ STATUS :INHERITED))))
462
463
464 _external_ if S is going to be inherited into any package that
465 /uses/ P by means of USE-PACKAGE, MAKE-PACKAGE, or
466 DEFPACKAGE.
467
468 Note that _external_ implies _present_, since to
469 make a symbol _external_, you'd have to use EXPORT
470 which will automatically make the symbol _present_.
471
472 You can check that with: (EQ (SYMBOL-STATUS S P) :EXTERNAL)
473
474
475 _internal_ if S is _accessible_ but not _external_.
476
477 You can check that with: (LET ((STATUS (SYMBOL-STATUS S P)))
478 (AND STATUS
479 (NOT (EQ STATUS :EXTERNAL))))
480
481
482 Notice that this is *different* to
483 (EQ (SYMBOL-STATUS S P) :INTERNAL)
484 because what the spec considers _internal_ is split up into two
485 explicit pieces: :INTERNAL, and :INHERITED; just as, for instance,
486 CL:FIND-SYMBOL does.
487
488 The rationale is that most times when you speak about \"internal\"
489 symbols, you're actually not including the symbols inherited
490 from other packages, but only about the symbols directly specific
491 to the package in question.
492 "
493 (when package ; may be NIL when symbol is completely uninterned.
494 (check-type symbol symbol) (check-type package package)
495 (multiple-value-bind (present-symbol status)
496 (find-symbol (symbol-name symbol) package)
497 (and (eq symbol present-symbol) status))))
498
499 (defun symbol-external-p (symbol &optional (package (symbol-package symbol)))
500 "True if SYMBOL is external in PACKAGE.
501 If PACKAGE is not specified, the home package of SYMBOL is used."
502 (eq (symbol-status symbol package) :external))
503
504
505 (defun classify-symbol (symbol)
506 "Returns a list of classifiers that classify SYMBOL according to its
507 underneath objects (e.g. :BOUNDP if SYMBOL constitutes a special
508 variable.) The list may contain the following classification
509 keywords: :BOUNDP, :FBOUNDP, :CONSTANT, :GENERIC-FUNCTION,
510 :TYPESPEC, :CLASS, :MACRO, :SPECIAL-OPERATOR, and/or :PACKAGE"
511 (check-type symbol symbol)
512 (flet ((type-specifier-p (s)
513 (or (documentation s 'type)
514 (not (eq (type-specifier-arglist s) :not-available)))))
515 (let (result)
516 (when (boundp symbol) (push (if (constantp symbol)
517 :constant :boundp) result))
518 (when (fboundp symbol) (push :fboundp result))
519 (when (type-specifier-p symbol) (push :typespec result))
520 (when (find-class symbol nil) (push :class result))
521 (when (macro-function symbol) (push :macro result))
522 (when (special-operator-p symbol) (push :special-operator result))
523 (when (find-package symbol) (push :package result))
524 (when (typep (ignore-errors (fdefinition symbol))
525 'generic-function)
526 (push :generic-function result))
527
528 result)))
529
530 (defun symbol-classification->string (flags)
531 (format nil "~A~A~A~A~A~A~A~A"
532 (if (or (member :boundp flags)
533 (member :constant flags)) "b" "-")
534 (if (member :fboundp flags) "f" "-")
535 (if (member :generic-function flags) "g" "-")
536 (if (member :class flags) "c" "-")
537 (if (member :typespec flags) "t" "-")
538 (if (member :macro flags) "m" "-")
539 (if (member :special-operator flags) "s" "-")
540 (if (member :package flags) "p" "-")))
541
542
543 ;;;; TCP Server
544
545 (defvar *use-dedicated-output-stream* nil
546 "When T swank will attempt to create a second connection to
547 Emacs which is used just to send output.")
548
549 (defvar *dedicated-output-stream-port* 0
550 "Which port we should use for the dedicated output stream.")
551
552 (defvar *communication-style* (preferred-communication-style))
553
554 (defvar *dont-close* nil
555 "Default value of :dont-close argument to start-server and
556 create-server.")
557
558 (defvar *dedicated-output-stream-buffering*
559 (if (eq *communication-style* :spawn) :full :none)
560 "The buffering scheme that should be used for the output stream.
561 Valid values are :none, :line, and :full.")
562
563 (defvar *coding-system* "iso-latin-1-unix")
564
565 (defvar *listener-sockets* nil
566 "A property list of lists containing style, socket pairs used
567 by swank server listeners, keyed on socket port number. They
568 are used to close sockets on server shutdown or restart.")
569
570 (defun start-server (port-file &key (style *communication-style*)
571 (dont-close *dont-close*)
572 (coding-system *coding-system*))
573 "Start the server and write the listen port number to PORT-FILE.
574 This is the entry point for Emacs."
575 (setup-server 0 (lambda (port)
576 (announce-server-port port-file port))
577 style dont-close
578 (find-external-format-or-lose coding-system)))
579
580 (defun create-server (&key (port default-server-port)
581 (style *communication-style*)
582 (dont-close *dont-close*)
583 (coding-system *coding-system*))
584 "Start a SWANK server on PORT running in STYLE.
585 If DONT-CLOSE is true then the listen socket will accept multiple
586 connections, otherwise it will be closed after the first."
587 (setup-server port #'simple-announce-function style dont-close
588 (find-external-format-or-lose coding-system)))
589
590 (defun find-external-format-or-lose (coding-system)
591 (or (find-external-format coding-system)
592 (error "Unsupported coding system: ~s" coding-system)))
593
594 (defparameter *loopback-interface* "127.0.0.1")
595
596 (defun setup-server (port announce-fn style dont-close external-format)
597 (declare (type function announce-fn))
598 (let* ((socket (create-socket *loopback-interface* port))
599 (local-port (local-port socket)))
600 (funcall announce-fn local-port)
601 (flet ((serve ()
602 (serve-connection socket style dont-close external-format)))
603 (ecase style
604 (:spawn
605 (initialize-multiprocessing
606 (lambda ()
607 (spawn (lambda ()
608 (cond ((not dont-close) (serve))
609 (t (loop (ignore-errors (serve))))))
610 :name (cat "Swank " (princ-to-string port))))))
611 ((:fd-handler :sigio)
612 (add-fd-handler socket (lambda () (serve))))
613 ((nil) (loop do (serve) while dont-close)))
614 (setf (getf *listener-sockets* port) (list style socket))
615 local-port)))
616
617 (defun stop-server (port)
618 "Stop server running on PORT."
619 (let* ((socket-description (getf *listener-sockets* port))
620 (style (first socket-description))
621 (socket (second socket-description)))
622 (ecase style
623 (:spawn
624 (let ((thread-position
625 (position-if
626 (lambda (x)
627 (string-equal (first x)
628 (concatenate 'string "Swank "
629 (princ-to-string port))))
630 (list-threads))))
631 (when thread-position
632 (kill-nth-thread thread-position)
633 (close-socket socket)
634 (remf *listener-sockets* port))))
635 ((:fd-handler :sigio)
636 (remove-fd-handlers socket)
637 (close-socket socket)
638 (remf *listener-sockets* port)))))
639
640 (defun restart-server (&key (port default-server-port)
641 (style *communication-style*)
642 (dont-close *dont-close*)
643 (coding-system *coding-system*))
644 "Stop the server listening on PORT, then start a new SWANK server
645 on PORT running in STYLE. If DONT-CLOSE is true then the listen socket
646 will accept multiple connections, otherwise it will be closed after the
647 first."
648 (stop-server port)
649 (sleep 5)
650 (create-server :port port :style style :dont-close dont-close
651 :coding-system coding-system))
652
653
654 (defun serve-connection (socket style dont-close external-format)
655 (let ((closed-socket-p nil))
656 (unwind-protect
657 (let ((client (accept-authenticated-connection
658 socket :external-format external-format)))
659 (unless dont-close
660 (close-socket socket)
661 (setf closed-socket-p t))
662 (let ((connection (create-connection client style)))
663 (run-hook *new-connection-hook* connection)
664 (push connection *connections*)
665 (serve-requests connection)))
666 (unless (or dont-close closed-socket-p)
667 (close-socket socket)))))
668
669 (defun accept-authenticated-connection (&rest args)
670 (let ((new (apply #'accept-connection args))
671 (success nil))
672 (unwind-protect
673 (let ((secret (slime-secret)))
674 (when secret
675 (set-stream-timeout new 20)
676 (let ((first-val (decode-message new)))
677 (unless (and (stringp first-val) (string= first-val secret))
678 (error "Incoming connection doesn't know the password."))))
679 (set-stream-timeout new nil)
680 (setf success t))
681 (unless success
682 (close new :abort t)))
683 new))
684
685 (defun slime-secret ()
686 "Finds the magic secret from the user's home directory. Returns nil
687 if the file doesn't exist; otherwise the first line of the file."
688 (with-open-file (in
689 (merge-pathnames (user-homedir-pathname) #p".slime-secret")
690 :if-does-not-exist nil)
691 (and in (read-line in nil ""))))
692
693 (defun serve-requests (connection)
694 "Read and process all requests on connections."
695 (funcall (connection.serve-requests connection) connection))
696
697 (defun announce-server-port (file port)
698 (with-open-file (s file
699 :direction :output
700 :if-exists :error
701 :if-does-not-exist :create)
702 (format s "~S~%" port))
703 (simple-announce-function port))
704
705 (defun simple-announce-function (port)
706 (when *swank-debug-p*
707 (format *log-output* "~&;; Swank started at port: ~D.~%" port)
708 (force-output *log-output*)))
709
710 (defun open-streams (connection)
711 "Return the 5 streams for IO redirection:
712 DEDICATED-OUTPUT INPUT OUTPUT IO REPL-RESULTS"
713 (let ((output-fn (make-output-function connection))
714 (input-fn
715 (lambda ()
716 (with-connection (connection)
717 (with-simple-restart (abort-read
718 "Abort reading input from Emacs.")
719 (read-user-input-from-emacs))))))
720 (multiple-value-bind (in out) (make-fn-streams input-fn output-fn)
721 (let* ((dedicated-output (if *use-dedicated-output-stream*
722 (open-dedicated-output-stream
723 (connection.socket-io connection))))
724 (out (or dedicated-output out))
725 (io (make-two-way-stream in out))
726 (repl-results (make-output-stream-for-target connection
727 :repl-result)))
728 (mapc #'make-stream-interactive (list in out io))
729 (values dedicated-output in out io repl-results)))))
730
731 ;; FIXME: if wait-for-event aborts the event will stay in the queue forever.
732 (defun make-output-function (connection)
733 "Create function to send user output to Emacs."
734 (let ((max 100) (i 0) (tag 0) (l 0))
735 (lambda (string)
736 (with-connection (connection)
737 (with-simple-restart (abort "Abort sending output to Emacs.")
738 (when (or (= i max) (> l (* 80 20 5)))
739 (setf tag (mod (1+ tag) 1000))
740 (send-to-emacs `(:ping ,(thread-id (current-thread)) ,tag))
741 (wait-for-event `(:emacs-pong ,tag))
742 (setf i 0)
743 (setf l 0))
744 (incf i)
745 (incf l (length string))
746 (send-to-emacs `(:write-string ,string)))))))
747
748 (defun make-output-function-for-target (connection target)
749 "Create a function to send user output to a specific TARGET in Emacs."
750 (lambda (string)
751 (with-connection (connection)
752 (with-simple-restart
753 (abort "Abort sending output to Emacs.")
754 (send-to-emacs `(:write-string ,string ,target))))))
755
756 (defun make-output-stream-for-target (connection target)
757 "Create a stream that sends output to a specific TARGET in Emacs."
758 (nth-value 1 (make-fn-streams
759 (lambda ()
760 (error "Should never be called"))
761 (make-output-function-for-target connection target))))
762
763 (defun open-dedicated-output-stream (socket-io)
764 "Open a dedicated output connection to the Emacs on SOCKET-IO.
765 Return an output stream suitable for writing program output.
766
767 This is an optimized way for Lisp to deliver output to Emacs."
768 (let ((socket (create-socket *loopback-interface*
769 *dedicated-output-stream-port*)))
770 (unwind-protect
771 (let ((port (local-port socket)))
772 (encode-message `(:open-dedicated-output-stream ,port) socket-io)
773 (let ((dedicated (accept-authenticated-connection
774 socket
775 :external-format
776 (or (ignore-errors
777 (stream-external-format socket-io))
778 :default)
779 :buffering *dedicated-output-stream-buffering*
780 :timeout 30)))
781 (close-socket socket)
782 (setf socket nil)
783 dedicated))
784 (when socket
785 (close-socket socket)))))
786
787 (defvar *sldb-quit-restart* 'abort
788 "What restart should swank attempt to invoke when the user sldb-quits.")
789
790 (defun handle-request (connection)
791 "Read and process one request. The processing is done in the extent
792 of the toplevel restart."
793 (assert (null *swank-state-stack*))
794 (let ((*swank-state-stack* '(:handle-request)))
795 (with-connection (connection)
796 (with-simple-restart (abort "Return to SLIME's top level.")
797 (let ((*sldb-quit-restart* (find-restart 'abort)))
798 (read-from-emacs))))))
799
800 (defun current-socket-io ()
801 (connection.socket-io *emacs-connection*))
802
803 (defun close-connection (c &optional condition backtrace)
804 (format *log-output* "~&;; swank:close-connection: ~A~%" condition)
805 (let ((cleanup (connection.cleanup c)))
806 (when cleanup
807 (funcall cleanup c)))
808 (close (connection.socket-io c))
809 (when (connection.dedicated-output c)
810 (close (connection.dedicated-output c)))
811 (setf *connections* (remove c *connections*))
812 (run-hook *connection-closed-hook* c)
813 (when (and condition (not (typep condition 'end-of-file)))
814 (finish-output *log-output*)
815 (format *log-output* "~&;; Event history start:~%")
816 (dump-event-history *log-output*)
817 (format *log-output* ";; Event history end.~%~
818 ;; Backtrace:~%~{~A~%~}~
819 ;; Connection to Emacs lost. [~%~
820 ;; condition: ~A~%~
821 ;; type: ~S~%~
822 ;; encoding: ~A style: ~S dedicated: ~S]~%"
823 backtrace
824 (escape-non-ascii (safe-condition-message condition) )
825 (type-of condition)
826 (ignore-errors (stream-external-format (connection.socket-io c)))
827 (connection.communication-style c)
828 *use-dedicated-output-stream*)
829 (finish-output *log-output*)))
830
831 (defvar *debug-on-swank-error* nil
832 "When non-nil internal swank errors will drop to a
833 debugger (not an sldb buffer). Do not set this to T unless you
834 want to debug swank internals.")
835
836 (defmacro with-reader-error-handler ((connection) &body body)
837 (let ((con (gensym))
838 (blck (gensym)))
839 `(let ((,con ,connection))
840 (block ,blck
841 (handler-bind ((swank-error
842 (lambda (e)
843 (if *debug-on-swank-error*
844 (invoke-debugger e)
845 (return-from ,blck
846 (close-connection
847 ,con
848 (swank-error.condition e)
849 (swank-error.backtrace e)))))))
850 (progn ,@body))))))
851
852 (defslimefun simple-break ()
853 (with-simple-restart (continue "Continue from interrupt.")
854 (call-with-debugger-hook
855 #'swank-debugger-hook
856 (lambda ()
857 (invoke-debugger
858 (make-condition 'simple-error
859 :format-control "Interrupt from Emacs")))))
860 nil)
861
862 ;;;;;; Thread based communication
863
864 (defvar *active-threads* '())
865
866 (defun read-loop (control-thread input-stream connection)
867 (with-reader-error-handler (connection)
868 (loop (send control-thread (decode-message input-stream)))))
869
870 (defun dispatch-loop (socket-io connection)
871 (let ((*emacs-connection* connection))
872 (handler-bind ((error (lambda (e)
873 (if *debug-on-swank-error*
874 (invoke-debugger e)
875 (return-from dispatch-loop
876 (close-connection connection e))))))
877 (loop (dispatch-event (receive) socket-io)))))
878
879 (defun repl-thread (connection)
880 (let ((thread (connection.repl-thread connection)))
881 (when (not thread)
882 (log-event "ERROR: repl-thread is nil"))
883 (assert thread)
884 (cond ((thread-alive-p thread)
885 thread)
886 (t
887 (setf (connection.repl-thread connection)
888 (spawn-repl-thread connection "new-repl-thread"))))))
889
890 (defun find-worker-thread (id)
891 (etypecase id
892 ((member t)
893 (car *active-threads*))
894 ((member :repl-thread)
895 (repl-thread *emacs-connection*))
896 (fixnum
897 (find-thread id))))
898
899 (defun interrupt-worker-thread (id)
900 (let ((thread (or (find-worker-thread id)
901 (repl-thread *emacs-connection*))))
902 (interrupt-thread thread #'simple-break)))
903
904 (defun thread-for-evaluation (id)
905 "Find or create a thread to evaluate the next request."
906 (let ((c *emacs-connection*))
907 (etypecase id
908 ((member t)
909 (spawn-worker-thread c))
910 ((member :repl-thread)
911 (repl-thread c))
912 (fixnum
913 (find-thread id)))))
914
915 (defun spawn-worker-thread (connection)
916 (spawn (lambda ()
917 (with-bindings *default-worker-thread-bindings*
918 (handle-request connection)))
919 :name "worker"))
920
921 (defun spawn-repl-thread (connection name)
922 (spawn (lambda ()
923 (with-bindings *default-worker-thread-bindings*
924 (repl-loop connection)))
925 :name name))
926
927 (defun dispatch-event (event socket-io)
928 "Handle an event triggered either by Emacs or within Lisp."
929 (log-event "DISPATCHING: ~S~%" event)
930 (destructure-case event
931 ((:emacs-rex form package thread-id id)
932 (let ((thread (thread-for-evaluation thread-id)))
933 (push thread *active-threads*)
934 (send thread `(:call eval-for-emacs ,form ,package ,id))))
935 ((:return thread &rest args)
936 (let ((tail (member thread *active-threads*)))
937 (setq *active-threads* (nconc (ldiff *active-threads* tail)
938 (cdr tail))))
939 (encode-message `(:return ,@args) socket-io))
940 ((:emacs-interrupt thread-id)
941 (interrupt-worker-thread thread-id))
942 (((:debug :debug-condition :debug-activate :debug-return)
943 thread &rest args)
944 (encode-message `(,(car event) ,(thread-id thread) ,@args) socket-io))
945 ((:read-string thread &rest args)
946 (encode-message `(:read-string ,(thread-id thread) ,@args) socket-io))
947 ((:y-or-n-p thread &rest args)
948 (encode-message `(:y-or-n-p ,(thread-id thread) ,@args) socket-io))
949 ((:read-aborted thread &rest args)
950 (encode-message `(:read-aborted ,(thread-id thread) ,@args) socket-io))
951 ((:emacs-return-string thread-id tag string)
952 (send (find-thread thread-id) `(:call take-input ,tag ,string)))
953 ((:eval thread &rest args)
954 (encode-message `(:eval ,(thread-id thread) ,@args) socket-io))
955 ((:emacs-return thread-id tag value)
956 (send (find-thread thread-id) `(:call take-input ,tag ,value)))
957 ((:emacs-pong thread-id tag)
958 (send (find-thread thread-id) `(:emacs-pong ,tag)))
959 (((:write-string :presentation-start :presentation-end
960 :new-package :new-features :ed :%apply :indentation-update
961 :eval-no-wait :background-message :inspect :ping)
962 &rest _)
963 (declare (ignore _))
964 (encode-message event socket-io))))
965
966 (defun spawn-threads-for-connection (connection)
967 (macrolet ((without-debugger-hook (&body body)
968 `(call-with-debugger-hook nil (lambda () ,@body))))
969 (let* ((socket-io (connection.socket-io connection))
970 (control-thread (spawn (lambda ()
971 (without-debugger-hook
972 (dispatch-loop socket-io connection)))
973 :name "control-thread")))
974 (setf (connection.control-thread connection) control-thread)
975 (let ((reader-thread (spawn (lambda ()
976 (let ((go (receive)))
977 (assert (eq go 'accept-input)))
978 (without-debugger-hook
979 (read-loop control-thread socket-io
980 connection)))
981 :name "reader-thread"))
982 (repl-thread (spawn-repl-thread connection "repl-thread")))
983 (setf (connection.repl-thread connection) repl-thread)
984 (setf (connection.reader-thread connection) reader-thread)
985 (send reader-thread 'accept-input)
986 connection))))
987
988 (defun cleanup-connection-threads (connection)
989 (let ((threads (list (connection.repl-thread connection)
990 (connection.reader-thread connection)
991 (connection.control-thread connection))))
992 (dolist (thread threads)
993 (when (and thread
994 (thread-alive-p thread)
995 (not (equal (current-thread) thread)))
996 (kill-thread thread)))))
997
998 (defun repl-loop (connection)
999 (loop (handle-request connection)))
1000
1001 (defun process-available-input (stream fn)
1002 (loop while (input-available-p stream)
1003 do (funcall fn)))
1004
1005 (defun input-available-p (stream)
1006 ;; return true iff we can read from STREAM without waiting or if we
1007 ;; hit EOF
1008 (let ((c (read-char-no-hang stream nil :eof)))
1009 (cond ((not c) nil)
1010 ((eq c :eof) t)
1011 (t
1012 (unread-char c stream)
1013 t))))
1014
1015 ;;;;;; Signal driven IO
1016
1017 (defun install-sigio-handler (connection)
1018 (let ((client (connection.socket-io connection)))
1019 (flet ((handler ()
1020 (cond ((null *swank-state-stack*)
1021 (with-reader-error-handler (connection)
1022 (process-available-input
1023 client (lambda () (handle-request connection)))))
1024 ((eq (car *swank-state-stack*) :read-next-form))
1025 (t (process-available-input client #'read-from-emacs)))))
1026 (add-sigio-handler client #'handler)
1027 (handler))))
1028
1029 (defun deinstall-sigio-handler (connection)
1030 (remove-sigio-handlers (connection.socket-io connection)))
1031
1032 ;;;;;; SERVE-EVENT based IO
1033
1034 (defun install-fd-handler (connection)
1035 (let ((client (connection.socket-io connection)))
1036 (flet ((handler ()
1037 (cond ((null *swank-state-stack*)
1038 (with-reader-error-handler (connection)
1039 (process-available-input
1040 client (lambda () (handle-request connection)))))
1041 ((eq (car *swank-state-stack*) :read-next-form))
1042 (t
1043 (process-available-input client #'read-from-emacs)))))
1044 ;;;; handle sigint
1045 ;;(install-debugger-globally
1046 ;; (lambda (c h)
1047 ;; (with-reader-error-handler (connection)
1048 ;; (block debugger
1049 ;; (with-connection (connection)
1050 ;; (swank-debugger-hook c h)
1051 ;; (return-from debugger))
1052 ;; (abort)))))
1053 (add-fd-handler client #'handler)
1054 (handler))))
1055
1056 (defun deinstall-fd-handler (connection)
1057 (remove-fd-handlers (connection.socket-io connection)))
1058
1059 ;;;;;; Simple sequential IO
1060
1061 (defun simple-serve-requests (connection)
1062 (unwind-protect
1063 (with-simple-restart (close-connection "Close SLIME connection")
1064 (with-reader-error-handler (connection)
1065 (loop
1066 (handle-request connection))))
1067 (close-connection connection)))
1068
1069 (defun read-from-socket-io ()
1070 (let ((event (decode-message (current-socket-io))))
1071 (log-event "DISPATCHING: ~S~%" event)
1072 (destructure-case event
1073 ((:emacs-rex form package thread id)
1074 (declare (ignore thread))
1075 `(:call eval-for-emacs ,form ,package ,id))
1076 ((:emacs-interrupt thread)
1077 (declare (ignore thread))
1078 '(:call simple-break))
1079 ((:emacs-return-string thread tag string)
1080 (declare (ignore thread))
1081 `(:call take-input ,tag ,string))
1082 ((:emacs-return thread tag value)
1083 (declare (ignore thread))
1084 `(:call take-input ,tag ,value))
1085 ((:emacs-pong thread tag)
1086 (declare (ignore thread))
1087 `(:emacs-pong ,tag)))))
1088
1089 (defun send-to-socket-io (event)
1090 (log-event "DISPATCHING: ~S~%" event)
1091 (flet ((send (o)
1092 (without-interrupts
1093 (encode-message o (current-socket-io)))))
1094 (destructure-case event
1095 (((:debug-activate :debug :debug-return :read-string :read-aborted
1096 :y-or-n-p :eval)
1097 thread &rest args)
1098 (declare (ignore thread))
1099 (send `(,(car event) 0 ,@args)))
1100 ((:return thread &rest args)
1101 (declare (ignore thread))
1102 (send `(:return ,@args)))
1103 (((:write-string :new-package :new-features :debug-condition
1104 :presentation-start :presentation-end
1105 :indentation-update :ed :%apply :eval-no-wait
1106 :background-message :inspect :ping)
1107 &rest _)
1108 (declare (ignore _))
1109 (send event)))))
1110
1111 (defun initialize-streams-for-connection (connection)
1112 (multiple-value-bind (dedicated in out io repl-results)
1113 (open-streams connection)
1114 (setf (connection.dedicated-output connection) dedicated
1115 (connection.user-io connection) io
1116 (connection.user-output connection) out
1117 (connection.user-input connection) in
1118 (connection.repl-results connection) repl-results)
1119 connection))
1120
1121 (defun create-connection (socket-io style)
1122 (let ((success nil))
1123 (unwind-protect
1124 (let ((c (ecase style
1125 (:spawn
1126 (make-connection :socket-io socket-io
1127 :read #'read-from-control-thread
1128 :send #'send-to-control-thread
1129 :serve-requests #'spawn-threads-for-connection
1130 :cleanup #'cleanup-connection-threads))
1131 (:sigio
1132 (make-connection :socket-io socket-io
1133 :read #'read-from-socket-io
1134 :send #'send-to-socket-io
1135 :serve-requests #'install-sigio-handler
1136 :cleanup #'deinstall-sigio-handler))
1137 (:fd-handler
1138 (make-connection :socket-io socket-io
1139 :read #'read-from-socket-io
1140 :send #'send-to-socket-io
1141 :serve-requests #'install-fd-handler
1142 :cleanup #'deinstall-fd-handler))
1143 ((nil)
1144 (make-connection :socket-io socket-io
1145 :read #'read-from-socket-io
1146 :send #'send-to-socket-io
1147 :serve-requests #'simple-serve-requests))
1148 )))
1149 (setf (connection.communication-style c) style)
1150 (initialize-streams-for-connection c)
1151 (setf success t)
1152 c)
1153 (unless success
1154 (close socket-io :abort t)))))
1155
1156
1157 ;;;; IO to Emacs
1158 ;;;
1159 ;;; This code handles redirection of the standard I/O streams
1160 ;;; (`*standard-output*', etc) into Emacs. The `connection' structure
1161 ;;; contains the appropriate streams, so all we have to do is make the
1162 ;;; right bindings.
1163
1164 ;;;;; Global I/O redirection framework
1165 ;;;
1166 ;;; Optionally, the top-level global bindings of the standard streams
1167 ;;; can be assigned to be redirected to Emacs. When Emacs connects we
1168 ;;; redirect the streams into the connection, and they keep going into
1169 ;;; that connection even if more are established. If the connection
1170 ;;; handling the streams closes then another is chosen, or if there
1171 ;;; are no connections then we revert to the original (real) streams.
1172 ;;;
1173 ;;; It is slightly tricky to assign the global values of standard
1174 ;;; streams because they are often shadowed by dynamic bindings. We
1175 ;;; solve this problem by introducing an extra indirection via synonym
1176 ;;; streams, so that *STANDARD-INPUT* is a synonym stream to
1177 ;;; *CURRENT-STANDARD-INPUT*, etc. We never shadow the "current"
1178 ;;; variables, so they can always be assigned to affect a global
1179 ;;; change.
1180
1181 (defvar *globally-redirect-io* nil
1182 "When non-nil globally redirect all standard streams to Emacs.")
1183
1184 ;;;;; Global redirection setup
1185
1186 (defvar *saved-global-streams* '()
1187 "A plist to save and restore redirected stream objects.
1188 E.g. the value for '*standard-output* holds the stream object
1189 for *standard-output* before we install our redirection.")
1190
1191 (defun setup-stream-indirection (stream-var &optional stream)
1192 "Setup redirection scaffolding for a global stream variable.
1193 Supposing (for example) STREAM-VAR is *STANDARD-INPUT*, this macro:
1194
1195 1. Saves the value of *STANDARD-INPUT* in `*SAVED-GLOBAL-STREAMS*'.
1196
1197 2. Creates *CURRENT-STANDARD-INPUT*, initially with the same value as
1198 *STANDARD-INPUT*.
1199
1200 3. Assigns *STANDARD-INPUT* to a synonym stream pointing to
1201 *CURRENT-STANDARD-INPUT*.
1202
1203 This has the effect of making *CURRENT-STANDARD-INPUT* contain the
1204 effective global value for *STANDARD-INPUT*. This way we can assign
1205 the effective global value even when *STANDARD-INPUT* is shadowed by a
1206 dynamic binding."
1207 (let ((current-stream-var (prefixed-var '#:current stream-var))
1208 (stream (or stream (symbol-value stream-var))))
1209 ;; Save the real stream value for the future.
1210 (setf (getf *saved-global-streams* stream-var) stream)
1211 ;; Define a new variable for the effective stream.
1212 ;; This can be reassigned.
1213 (proclaim `(special ,current-stream-var))
1214 (set current-stream-var stream)
1215 ;; Assign the real binding as a synonym for the current one.
1216 (set stream-var (make-synonym-stream current-stream-var))))
1217
1218 (defun prefixed-var (prefix variable-symbol)
1219 "(PREFIXED-VAR \"FOO\" '*BAR*) => SWANK::*FOO-BAR*"
1220 (let ((basename (subseq (symbol-name variable-symbol) 1)))
1221 (intern (format nil "*~A-~A" (string prefix) basename) :swank)))
1222
1223 (defvar *standard-output-streams*
1224 '(*standard-output* *error-output* *trace-output*)
1225 "The symbols naming standard output streams.")
1226
1227 (defvar *standard-input-streams*
1228 '(*standard-input*)
1229 "The symbols naming standard input streams.")
1230
1231 (defvar *standard-io-streams*
1232 '(*debug-io* *query-io* *terminal-io*)
1233 "The symbols naming standard io streams.")
1234
1235 (defun init-global-stream-redirection ()
1236 (when *globally-redirect-io*
1237 (assert (not *saved-global-streams*) () "Streams already redirected.")
1238 (mapc #'setup-stream-indirection
1239 (append *standard-output-streams*
1240 *standard-input-streams*
1241 *standard-io-streams*))))
1242
1243 (add-hook *after-init-hook* 'init-global-stream-redirection)
1244
1245 (defun globally-redirect-io-to-connection (connection)
1246 "Set the standard I/O streams to redirect to CONNECTION.
1247 Assigns *CURRENT-<STREAM>* for all standard streams."
1248 (dolist (o *standard-output-streams*)
1249 (set (prefixed-var '#:current o)
1250 (connection.user-output connection)))
1251 ;; FIXME: If we redirect standard input to Emacs then we get the
1252 ;; regular Lisp top-level trying to read from our REPL.
1253 ;;
1254 ;; Perhaps the ideal would be for the real top-level to run in a
1255 ;; thread with local bindings for all the standard streams. Failing
1256 ;; that we probably would like to inhibit it from reading while
1257 ;; Emacs is connected.
1258 ;;
1259 ;; Meanwhile we just leave *standard-input* alone.
1260 #+NIL
1261 (dolist (i *standard-input-streams*)
1262 (set (prefixed-var '#:current i)
1263 (connection.user-input connection)))
1264 (dolist (io *standard-io-streams*)
1265 (set (prefixed-var '#:current io)
1266 (connection.user-io connection))))
1267
1268 (defun revert-global-io-redirection ()
1269 "Set *CURRENT-<STREAM>* to *REAL-<STREAM>* for all standard streams."
1270 (dolist (stream-var (append *standard-output-streams*
1271 *standard-input-streams*
1272 *standard-io-streams*))
1273 (set (prefixed-var '#:current stream-var)
1274 (getf *saved-global-streams* stream-var))))
1275
1276 ;;;;; Global redirection hooks
1277
1278 (defvar *global-stdio-connection* nil
1279 "The connection to which standard I/O streams are globally redirected.
1280 NIL if streams are not globally redirected.")
1281
1282 (defun maybe-redirect-global-io (connection)
1283 "Consider globally redirecting to a newly-established CONNECTION."
1284 (when (and *globally-redirect-io* (null *global-stdio-connection*))
1285 (setq *global-stdio-connection* connection)
1286 (globally-redirect-io-to-connection connection)))
1287
1288 (defun update-redirection-after-close (closed-connection)
1289 "Update redirection after a connection closes."
1290 (check-type closed-connection connection)
1291 (when (eq *global-stdio-connection* closed-connection)
1292 (if (and (default-connection) *globally-redirect-io*)
1293 ;; Redirect to another connection.
1294 (globally-redirect-io-to-connection (default-connection))
1295 ;; No more connections, revert to the real streams.
1296 (progn (revert-global-io-redirection)
1297 (setq *global-stdio-connection* nil)))))
1298
1299 (add-hook *new-connection-hook* 'maybe-redirect-global-io)
1300 (add-hook *connection-closed-hook* 'update-redirection-after-close)
1301
1302 ;;;;; Redirection during requests
1303 ;;;
1304 ;;; We always redirect the standard streams to Emacs while evaluating
1305 ;;; an RPC. This is done with simple dynamic bindings.
1306
1307 (defun call-with-redirected-io (connection function)
1308 "Call FUNCTION with I/O streams redirected via CONNECTION."
1309 (declare (type function function))
1310 (let* ((io (connection.user-io connection))
1311 (in (connection.user-input connection))
1312 (out (connection.user-output connection))
1313 (trace (or (connection.trace-output connection) out))
1314 (*standard-output* out)
1315 (*error-output* out)
1316 (*trace-output* trace)
1317 (*debug-io* io)
1318 (*query-io* io)
1319 (*standard-input* in)
1320 (*terminal-io* io))
1321 (funcall function)))
1322
1323 (defun call-with-thread-description (description thunk)
1324 (let* ((thread (current-thread))
1325 (old-description (thread-description thread)))
1326 (set-thread-description thread description)
1327 (unwind-protect (funcall thunk)
1328 (set-thread-description thread old-description))))
1329
1330 (defmacro with-thread-description (description &body body)
1331 `(call-with-thread-description ,description #'(lambda () ,@body)))
1332
1333 (defvar *event-queue* '())
1334
1335 (defun read-from-emacs ()
1336 "Read and process a request from Emacs."
1337 (flet ((request-to-string (req)
1338 (remove #\Newline
1339 (string-trim '(#\Space #\Tab)
1340 (prin1-to-string req))))
1341 (truncate-string (str n)
1342 (if (> (length str) n)
1343 (format nil "~A..." (subseq str 0 n))
1344 str)))
1345 (let ((request (funcall (connection.read *emacs-connection*))))
1346 (if (eq *communication-style* :spawn)
1347 ;; For `M-x slime-list-threads': Display what threads
1348 ;; created by swank are currently doing.
1349 (with-thread-description (truncate-string (request-to-string request) 55)
1350 (apply #'funcall request))
1351 (destructure-case request
1352 ((:call &rest args) (apply #'funcall args))
1353 (t (setf *event-queue*
1354 (nconc *event-queue* (list request)))))))))
1355
1356 (defun wait-for-event (pattern)
1357 (log-event "wait-for-event: %S~%" pattern)
1358 (case (connection.communication-style *emacs-connection*)
1359 (:spawn (receive-if (lambda (e) (event-match-p e pattern))))
1360 (t (wait-for-event/event-loop pattern))))
1361
1362 (defun wait-for-event/event-loop (pattern)
1363 (loop
1364 (let ((tail (member-if (lambda (e) (event-match-p e pattern))
1365 *event-queue*)))
1366 (cond (tail
1367 (setq *event-queue*
1368 (nconc (ldiff *event-queue* tail) (cdr tail)))
1369 (return (car tail)))
1370 (t
1371 (let ((event (read-from-socket-io)))
1372 (cond ((event-match-p event pattern) (return event))
1373 ((eq (car event) :call)
1374 (apply #'funcall (cdr event)))
1375 (t
1376 (setf *event-queue*
1377 (nconc *event-queue* (list event)))))))))))
1378
1379 (defun event-match-p (event pattern)
1380 (cond ((or (keywordp pattern) (numberp pattern) (stringp pattern)
1381 (member pattern '(nil t)))
1382 (equal event pattern))
1383 ((symbolp pattern) t)
1384 ((consp pattern)
1385 (and (consp event)
1386 (and (event-match-p (car event) (car pattern))
1387 (event-match-p (cdr event) (cdr pattern)))))
1388 (t (error "Invalid pattern: ~S" pattern))))
1389
1390 (defun read-from-control-thread ()
1391 (cdr (receive-if (lambda (e) (event-match-p e '(:call . _))))))
1392
1393 (defun decode-message (stream)
1394 "Read an S-expression from STREAM using the SLIME protocol."
1395 (let ((*swank-state-stack* (cons :read-next-form *swank-state-stack*)))
1396 (handler-bind ((error (lambda (c) (error (make-swank-error c)))))
1397 (let* ((length (decode-message-length stream))
1398 (string (make-string length))
1399 (pos (read-sequence string stream)))
1400 (assert (= pos length) ()
1401 "Short read: length=~D pos=~D" length pos)
1402 (log-event "READ: ~S~%" string)
1403 (read-form string)))))
1404
1405 (defun decode-message-length (stream)
1406 (let ((buffer (make-string 6)))
1407 (dotimes (i 6)
1408 (setf (aref buffer i) (read-char stream)))
1409 (parse-integer buffer :radix #x10)))
1410
1411 (defun read-form (string)
1412 (with-standard-io-syntax
1413 (let ((*package* *swank-io-package*))
1414 (read-from-string string))))
1415
1416 (defvar *slime-features* nil
1417 "The feature list that has been sent to Emacs.")
1418
1419 (defun send-to-emacs (object)
1420 "Send OBJECT to Emacs."
1421 (funcall (connection.send *emacs-connection*) object))
1422
1423 (defun send-oob-to-emacs (object)
1424 (send-to-emacs object))
1425
1426 (defun send-to-control-thread (object)
1427 (send (connection.control-thread *emacs-connection*) object))
1428
1429 (defun encode-message (message stream)
1430 (let* ((string (prin1-to-string-for-emacs message))
1431 (length (length string)))
1432 (log-event "WRITE: ~A~%" string)
1433 (without-interrupts
1434 (let ((*print-pretty* nil))
1435 (format stream "~6,'0x" length))
1436 (write-string string stream))
1437 ;;(terpri stream)
1438 (finish-output stream)))
1439
1440 (defun prin1-to-string-for-emacs (object)
1441 (with-standard-io-syntax
1442 (let ((*print-case* :downcase)
1443 (*print-readably* nil)
1444 (*print-pretty* nil)
1445 (*package* *swank-io-package*))
1446 (prin1-to-string object))))
1447
1448 (defun force-user-output ()
1449 (force-output (connection.user-io *emacs-connection*)))
1450
1451 (defun clear-user-input ()
1452 (clear-input (connection.user-input *emacs-connection*)))
1453
1454 (defvar *read-input-catch-tag* 0)
1455
1456 (defun intern-catch-tag (tag)
1457 ;; fixnums aren't eq in ABCL, so we use intern to create tags
1458 (intern (format nil "~D" tag) :swank))
1459
1460 (defun read-user-input-from-emacs ()
1461 (let ((tag (incf *read-input-catch-tag*)))
1462 (force-output)
1463 (send-to-emacs `(:read-string ,(current-thread) ,tag))
1464 (let ((ok nil))
1465 (unwind-protect
1466 (prog1 (catch (intern-catch-tag tag)
1467 (loop (read-from-emacs)))
1468 (setq ok t))
1469 (unless ok
1470 (send-to-emacs `(:read-aborted ,(current-thread) ,tag)))))))
1471
1472 (defun y-or-n-p-in-emacs (format-string &rest arguments)
1473 "Like y-or-n-p, but ask in the Emacs minibuffer."
1474 (let ((tag (incf *read-input-catch-tag*))
1475 (question (apply #'format nil format-string arguments)))
1476 (force-output)
1477 (send-to-emacs `(:y-or-n-p ,(current-thread) ,tag ,question))
1478 (catch (intern-catch-tag tag)
1479 (loop (read-from-emacs)))))
1480
1481 (defslimefun take-input (tag input)
1482 "Return the string INPUT to the continuation TAG."
1483 (throw (intern-catch-tag tag) input))
1484
1485 (defun process-form-for-emacs (form)
1486 "Returns a string which emacs will read as equivalent to
1487 FORM. FORM can contain lists, strings, characters, symbols and
1488 numbers.
1489
1490 Characters are converted emacs' ?<char> notaion, strings are left
1491 as they are (except for espacing any nested \" chars, numbers are
1492 printed in base 10 and symbols are printed as their symbol-name
1493 converted to lower case."
1494 (etypecase form
1495 (string (format nil "~S" form))
1496 (cons (format nil "(~A . ~A)"
1497 (process-form-for-emacs (car form))
1498 (process-form-for-emacs (cdr form))))
1499 (character (format nil "?~C" form))
1500 (symbol (concatenate 'string (when (eq (symbol-package form)
1501 #.(find-package "KEYWORD"))
1502 ":")
1503 (string-downcase (symbol-name form))))
1504 (number (let ((*print-base* 10))
1505 (princ-to-string form)))))
1506
1507 (defun eval-in-emacs (form &optional nowait)
1508 "Eval FORM in Emacs."
1509 (cond (nowait
1510 (send-to-emacs `(:eval-no-wait ,(process-form-for-emacs form))))
1511 (t
1512 (force-output)
1513 (let* ((tag (incf *read-input-catch-tag*))
1514 (value (catch (intern-catch-tag tag)
1515 (send-to-emacs
1516 `(:eval ,(current-thread) ,tag
1517 ,(process-form-for-emacs form)))
1518 (loop (read-from-emacs)))))
1519 (destructure-case value
1520 ((:ok value) value)
1521 ((:abort) (abort)))))))
1522
1523 (defvar *swank-wire-protocol-version* nil
1524 "The version of the swank/slime communication protocol.")
1525
1526 (defslimefun connection-info ()
1527 "Return a key-value list of the form:
1528 \(&key PID STYLE LISP-IMPLEMENTATION MACHINE FEATURES PACKAGE VERSION)
1529 PID: is the process-id of Lisp process (or nil, depending on the STYLE)
1530 STYLE: the communication style
1531 LISP-IMPLEMENTATION: a list (&key TYPE NAME VERSION)
1532 FEATURES: a list of keywords
1533 PACKAGE: a list (&key NAME PROMPT)
1534 VERSION: the protocol version"
1535 (setq *slime-features* *features*)
1536 `(:pid ,(getpid) :style ,(connection.communication-style *emacs-connection*)
1537 :lisp-implementation (:type ,(lisp-implementation-type)
1538 :name ,(lisp-implementation-type-name)
1539 :version ,(lisp-implementation-version))
1540 :machine (:instance ,(machine-instance)
1541 :type ,(machine-type)
1542 :version ,(machine-version))
1543 :features ,(features-for-emacs)
1544 :modules ,*modules*
1545 :package (:name ,(package-name *package*)
1546 :prompt ,(package-string-for-prompt *package*))
1547 :version ,*swank-wire-protocol-version*))
1548
1549 (defslimefun io-speed-test (&optional (n 1000) (m 1))
1550 (let* ((s *standard-output*)
1551 (*trace-output* (make-broadcast-stream s *log-output*)))
1552 (time (progn
1553 (dotimes (i n)
1554 (format s "~D abcdefghijklm~%" i)
1555 (when (zerop (mod n m))
1556 (finish-output s)))
1557 (finish-output s)
1558 (when *emacs-connection*
1559 (eval-in-emacs '(message "done.")))))
1560 (terpri *trace-output*)
1561 (finish-output *trace-output*)
1562 nil))
1563
1564
1565 ;;;; Reading and printing
1566
1567 (defmacro define-special (name doc)
1568 "Define a special variable NAME with doc string DOC.
1569 This is like defvar, but NAME will not be initialized."
1570 `(progn
1571 (defvar ,name)
1572 (setf (documentation ',name 'variable) ,doc)))
1573
1574 (define-special *buffer-package*
1575 "Package corresponding to slime-buffer-package.
1576
1577 EVAL-FOR-EMACS binds *buffer-package*. Strings originating from a slime
1578 buffer are best read in this package. See also FROM-STRING and TO-STRING.")
1579
1580 (define-special *buffer-readtable*
1581 "Readtable associated with the current buffer")
1582
1583 (defmacro with-buffer-syntax ((&rest _) &body body)
1584 "Execute BODY with appropriate *package* and *readtable* bindings.
1585
1586 This should be used for code that is conceptionally executed in an
1587 Emacs buffer."
1588 (destructuring-bind () _
1589 `(call-with-buffer-syntax (lambda () ,@body))))
1590
1591 (defun call-with-buffer-syntax (fun)
1592 (let ((*package* *buffer-package*))
1593 ;; Don't shadow *readtable* unnecessarily because that prevents
1594 ;; the user from assigning to it.
1595 (if (eq *readtable* *buffer-readtable*)
1596 (call-with-syntax-hooks fun)
1597 (let ((*readtable* *buffer-readtable*))
1598 (call-with-syntax-hooks fun)))))
1599
1600 (defun to-string (object)
1601 "Write OBJECT in the *BUFFER-PACKAGE*.
1602 The result may not be readable. Handles problems with PRINT-OBJECT methods
1603 gracefully."
1604 (with-buffer-syntax ()
1605 (let ((*print-readably* nil))
1606 (handler-case
1607 (prin1-to-string object)
1608 (error ()
1609 (with-output-to-string (s)
1610 (print-unreadable-object (object s :type t :identity t)
1611 (princ "<<error printing object>>" s))))))))
1612
1613 (defun from-string (string)
1614 "Read string in the *BUFFER-PACKAGE*"
1615 (with-buffer-syntax ()
1616 (let ((*read-suppress* nil))
1617 (read-from-string string))))
1618
1619 ;; FIXME: deal with #\| etc. hard to do portably.
1620 (defun tokenize-symbol (string)
1621 "STRING is interpreted as the string representation of a symbol
1622 and is tokenized accordingly. The result is returned in three
1623 values: The package identifier part, the actual symbol identifier
1624 part, and a flag if the STRING represents a symbol that is
1625 internal to the package identifier part. (Notice that the flag is
1626 also true with an empty package identifier part, as the STRING is
1627 considered to represent a symbol internal to some current package.)"
1628 (let ((package (let ((pos (position #\: string)))
1629 (if pos (subseq string 0 pos) nil)))
1630 (symbol (let ((pos (position #\: string :from-end t)))
1631 (if pos (subseq string (1+ pos)) string)))
1632 (internp (not (= (count #\: string) 1))))
1633 (values symbol package internp)))
1634
1635 (defun tokenize-symbol-thoroughly (string)
1636 "This version of TOKENIZE-SYMBOL handles escape characters."
1637 (let ((package nil)
1638 (token (make-array (length string) :element-type 'character
1639 :fill-pointer 0))
1640 (backslash nil)
1641 (vertical nil)
1642 (internp nil))
1643 (loop for char across string
1644 do (cond
1645 (backslash
1646 (vector-push-extend char token)
1647 (setq backslash nil))
1648 ((char= char #\\) ; Quotes next character, even within |...|
1649 (setq backslash t))
1650 ((char= char #\|)
1651 (setq vertical t))
1652 (vertical
1653 (vector-push-extend char token))
1654 ((char= char #\:)
1655 (if package
1656 (setq internp t)
1657 (setq package token
1658 token (make-array (length string)
1659 :element-type 'character
1660 :fill-pointer 0))))
1661 (t
1662 (vector-push-extend (casify-char char) token))))
1663 (values token package (or (not package) internp))))
1664
1665 (defun untokenize-symbol (package-name internal-p symbol-name)
1666 "The inverse of TOKENIZE-SYMBOL.
1667
1668 (untokenize-symbol \"quux\" nil \"foo\") ==> \"quux:foo\"
1669 (untokenize-symbol \"quux\" t \"foo\") ==> \"quux::foo\"
1670 (untokenize-symbol nil nil \"foo\") ==> \"foo\"
1671 "
1672 (cond ((not package-name) symbol-name)
1673 (internal-p (cat package-name "::" symbol-name))
1674 (t (cat package-name ":" symbol-name))))
1675
1676 (defun casify-char (char)
1677 "Convert CHAR accoring to readtable-case."
1678 (ecase (readtable-case *readtable*)
1679 (:preserve char)
1680 (:upcase (char-upcase char))
1681 (:downcase (char-downcase char))
1682 (:invert (if (upper-case-p char)
1683 (char-downcase char)
1684 (char-upcase char)))))
1685
1686 (defun parse-symbol (string &optional (package *package*))
1687 "Find the symbol named STRING.
1688 Return the symbol and a flag indicating whether the symbols was found."
1689 (multiple-value-bind (sname pname) (tokenize-symbol-thoroughly string)
1690 (let ((package (cond ((string= pname "") keyword-package)
1691 (pname (find-package pname))
1692 (t package))))
1693 (if package
1694 (multiple-value-bind (symbol flag) (find-symbol sname package)
1695 (values symbol flag sname package))
1696 (values nil nil nil nil)))))
1697
1698 (defun parse-symbol-or-lose (string &optional (package *package*))
1699 (multiple-value-bind (symbol status) (parse-symbol string package)
1700 (if status
1701 (values symbol status)
1702 (error "Unknown symbol: ~A [in ~A]" string package))))
1703
1704 (defun parse-package (string)
1705 "Find the package named STRING.
1706 Return the package or nil."
1707 ;; STRING comes usually from a (in-package STRING) form.
1708 (ignore-errors
1709 (find-package (let ((*package* *swank-io-package*))
1710 (read-from-string string)))))
1711
1712 (defun unparse-name (string)
1713 "Print the name STRING according to the current printer settings."
1714 ;; this is intended for package or symbol names
1715 (subseq (prin1-to-string (make-symbol string)) 2))
1716
1717 (defun guess-package (string)
1718 "Guess which package corresponds to STRING.
1719 Return nil if no package matches."
1720 (or (find-package string)
1721 (parse-package string)
1722 (if (find #\! string) ; for SBCL
1723 (guess-package (substitute #\- #\! string)))))
1724
1725 (defvar *readtable-alist* (default-readtable-alist)
1726 "An alist mapping package names to readtables.")
1727
1728 (defun guess-buffer-readtable (package-name)
1729 (let ((package (guess-package package-name)))
1730 (or (and package
1731 (cdr (assoc (package-name package) *readtable-alist*
1732 :test #'string=)))
1733 *readtable*)))
1734
1735
1736 ;;;; Evaluation
1737
1738 (defvar *pending-continuations* '()
1739 "List of continuations for Emacs. (thread local)")
1740
1741 (defun guess-buffer-package (string)
1742 "Return a package for STRING.
1743 Fall back to the the current if no such package exists."
1744 (or (and string (guess-package string))
1745 *package*))
1746
1747 (defun eval-for-emacs (form buffer-package id)
1748 "Bind *BUFFER-PACKAGE* to BUFFER-PACKAGE and evaluate FORM.
1749 Return the result to the continuation ID.
1750 Errors are trapped and invoke our debugger."
1751 (call-with-debugger-hook
1752 #'swank-debugger-hook
1753 (lambda ()
1754 (let (ok result)
1755 (unwind-protect
1756 (let ((*buffer-package* (guess-buffer-package buffer-package))
1757 (*buffer-readtable* (guess-buffer-readtable buffer-package))
1758 (*pending-continuations* (cons id *pending-continuations*)))
1759 (check-type *buffer-package* package)
1760 (check-type *buffer-readtable* readtable)
1761 ;; APPLY would be cleaner than EVAL.
1762 ;;(setq result (apply (car form) (cdr form)))
1763 (setq result (eval form))
1764 (run-hook *pre-reply-hook*)
1765 (setq ok t))
1766 (send-to-emacs `(:return ,(current-thread)
1767 ,(if ok
1768 `(:ok ,result)
1769 `(:abort))
1770 ,id)))))))
1771
1772 (defvar *echo-area-prefix* "=> "
1773 "A prefix that `format-values-for-echo-area' should use.")
1774
1775 (defun format-values-for-echo-area (values)
1776 (with-buffer-syntax ()
1777 (let ((*print-readably* nil))
1778 (cond ((null values) "; No value")
1779 ((and (integerp (car values)) (null (cdr values)))
1780 (let ((i (car values)))
1781 (format nil "~A~D (#x~X, #o~O, #b~B)"
1782 *echo-area-prefix* i i i i)))
1783 (t (format nil "~a~{~S~^, ~}" *echo-area-prefix* values))))))
1784
1785 (defslimefun interactive-eval (string)
1786 (with-buffer-syntax ()
1787 (let ((values (multiple-value-list (eval (from-string string)))))
1788 (fresh-line)
1789 (finish-output)
1790 (format-values-for-echo-area values))))
1791
1792 (defslimefun eval-and-grab-output (string)
1793 (with-buffer-syntax ()
1794 (let* ((s (make-string-output-stream))
1795 (*standard-output* s)
1796 (values (multiple-value-list (eval (from-string string)))))
1797 (list (get-output-stream-string s)
1798 (format nil "~{~S~^~%~}" values)))))
1799
1800 (defun eval-region (string)
1801 "Evaluate STRING.
1802 Return the results of the last form as a list and as secondary value the
1803 last form."
1804 (with-input-from-string (stream string)
1805 (let (- values)
1806 (loop
1807 (let ((form (read stream nil stream)))
1808 (when (eq form stream)
1809 (return (values values -)))
1810 (setq - form)
1811 (setq values (multiple-value-list (eval form)))
1812 (finish-output))))))
1813
1814 (defslimefun interactive-eval-region (string)
1815 (with-buffer-syntax ()
1816 (format-values-for-echo-area (eval-region string))))
1817
1818 (defslimefun re-evaluate-defvar (form)
1819 (with-buffer-syntax ()
1820 (let ((form (read-from-string form)))
1821 (destructuring-bind (dv name &optional value doc) form
1822 (declare (ignore value doc))
1823 (assert (eq dv 'defvar))
1824 (makunbound name)
1825 (prin1-to-string (eval form))))))
1826
1827 (defvar *swank-pprint-bindings*
1828 `((*print-pretty* . t)
1829 (*print-level* . nil)
1830 (*print-length* . nil)
1831 (*print-circle* . t)
1832 (*print-gensym* . t)
1833 (*print-readably* . nil))
1834 "A list of variables bindings during pretty printing.
1835 Used by pprint-eval.")
1836
1837 (defun swank-pprint (list)
1838 "Bind some printer variables and pretty print each object in LIST."
1839 (with-buffer-syntax ()
1840 (with-bindings *swank-pprint-bindings*
1841 (cond ((null list) "; No value")
1842 (t (with-output-to-string (*standard-output*)
1843 (dolist (o list)
1844 (pprint o)
1845 (terpri))))))))
1846
1847 (defslimefun pprint-eval (string)
1848 (with-buffer-syntax ()
1849 (swank-pprint (multiple-value-list (eval (read-from-string string))))))
1850
1851 (defslimefun set-package (name)
1852 "Set *package* to the package named NAME.
1853 Return the full package-name and the string to use in the prompt."
1854 (let ((p (guess-package name)))
1855 (assert (packagep p))
1856 (setq *package* p)
1857 (list (package-name p) (package-string-for-prompt p))))
1858
1859 ;;;;; Listener eval
1860
1861 (defvar *listener-eval-function* 'repl-eval)
1862
1863 (defslimefun listener-eval (string)
1864 (funcall *listener-eval-function* string))
1865
1866 (defvar *send-repl-results-function* 'send-repl-results-to-emacs)
1867
1868 (defun repl-eval (string)
1869 (clear-user-input)
1870 (with-buffer-syntax ()
1871 (track-package
1872 (lambda ()
1873 (multiple-value-bind (values last-form) (eval-region string)
1874 (setq *** ** ** * * (car values)
1875 /// // // / / values
1876 +++ ++ ++ + + last-form)
1877 (funcall *send-repl-results-function* values)))))
1878 nil)
1879
1880 (defun track-package (fun)
1881 (let ((p *package*))
1882 (unwind-protect (funcall fun)
1883 (unless (eq *package* p)
1884 (send-to-emacs (list :new-package (package-name *package*)
1885 (package-string-for-prompt *package*)))))))
1886
1887 (defun send-repl-results-to-emacs (values)
1888 (fresh-line)
1889 (finish-output)
1890 (if (null values)
1891 (send-to-emacs `(:write-string "; No value" :repl-result))
1892 (dolist (v values)
1893 (send-to-emacs `(:write-string ,(cat (prin1-to-string v) #\newline)
1894 :repl-result)))))
1895
1896 (defun cat (&rest strings)
1897 "Concatenate all arguments and make the result a string."
1898 (with-output-to-string (out)
1899 (dolist (s strings)
1900 (etypecase s
1901 (string (write-string s out))
1902 (character (write-char s out))))))
1903
1904 (defun package-string-for-prompt (package)
1905 "Return the shortest nickname (or canonical name) of PACKAGE."
1906 (unparse-name
1907 (or (canonical-package-nickname package)
1908 (auto-abbreviated-package-name package)
1909 (shortest-package-nickname package))))
1910
1911 (defun canonical-package-nickname (package)
1912 "Return the canonical package nickname, if any, of PACKAGE."
1913 (let ((name (cdr (assoc (package-name package) *canonical-package-nicknames*
1914 :test #'string=))))
1915 (and name (string name))))
1916
1917 (defun auto-abbreviated-package-name (package)
1918 "Return an abbreviated 'name' for PACKAGE.
1919
1920 N.B. this is not an actual package name or nickname."
1921 (when *auto-abbreviate-dotted-packages*
1922 (let ((last-dot (position #\. (package-name package) :from-end t)))
1923 (when last-dot (subseq (package-name package) (1+ last-dot))))))
1924
1925 (defun shortest-package-nickname (package)
1926 "Return the shortest nickname (or canonical name) of PACKAGE."
1927 (loop for name in (cons (package-name package) (package-nicknames package))
1928 for shortest = name then (if (< (length name) (length shortest))
1929 name
1930 shortest)
1931 finally (return shortest)))
1932
1933 (defslimefun ed-in-emacs (&optional what)
1934 "Edit WHAT in Emacs.
1935
1936 WHAT can be:
1937 A pathname or a string,
1938 A list (PATHNAME-OR-STRING LINE [COLUMN]),
1939 A function name (symbol or cons),
1940 NIL.
1941
1942 Returns true if it actually called emacs, or NIL if not."
1943 (flet ((pathname-or-string-p (thing)
1944 (or (pathnamep thing) (typep thing 'string)))
1945 (canonicalize-filename (filename)
1946 (namestring (or (probe-file filename) filename))))
1947 (let ((target
1948 (cond ((and (listp what) (pathname-or-string-p (first what)))
1949 (cons (canonicalize-filename (car what)) (cdr what)))
1950 ((pathname-or-string-p what)
1951 (canonicalize-filename what))
1952 ((symbolp what) what)
1953 ((consp what) what)
1954 (t (return-from ed-in-emacs nil)))))
1955 (cond
1956 (*emacs-connection* (send-oob-to-emacs `(:ed ,target)))
1957 ((default-connection)
1958 (with-connection ((default-connection))
1959 (send-oob-to-emacs `(:ed ,target))))
1960 (t nil)))))
1961
1962 (defslimefun inspect-in-emacs (what)
1963 "Inspect WHAT in Emacs."
1964 (flet ((send-it ()
1965 (with-buffer-syntax ()
1966 (reset-inspector)
1967 (send-oob-to-emacs `(:inspect ,(inspect-object what))))))
1968 (cond
1969 (*emacs-connection*
1970 (send-it))
1971 ((default-connection)
1972 (with-connection ((default-connection))
1973 (send-it))))
1974 what))
1975
1976 (defslimefun value-for-editing (form)
1977 "Return a readable value of FORM for editing in Emacs.
1978 FORM is expected, but not required, to be SETF'able."
1979 ;; FIXME: Can we check FORM for setfability? -luke (12/Mar/2005)
1980 (with-buffer-syntax ()
1981 (prin1-to-string (eval (read-from-string form)))))
1982
1983 (defslimefun commit-edited-value (form value)
1984 "Set the value of a setf'able FORM to VALUE.
1985 FORM and VALUE are both strings from Emacs."
1986 (with-buffer-syntax ()
1987 (eval `(setf ,(read-from-string form)
1988 ,(read-from-string (concatenate 'string "`" value))))
1989 t))
1990
1991 (defun background-message (format-string &rest args)
1992 "Display a message in Emacs' echo area.
1993
1994 Use this function for informative messages only. The message may even
1995 be dropped, if we are too busy with other things."
1996 (when *emacs-connection*
1997 (send-to-emacs `(:background-message
1998 ,(apply #'format nil format-string args)))))
1999
2000
2001 ;;;; Debugger
2002
2003 (defun swank-debugger-hook (condition hook)
2004 "Debugger function for binding *DEBUGGER-HOOK*.
2005 Sends a message to Emacs declaring that the debugger has been entered,
2006 then waits to handle further requests from Emacs. Eventually returns
2007 after Emacs causes a restart to be invoked."
2008 (declare (ignore hook))
2009 (cond (*emacs-connection*
2010 (debug-in-emacs condition))
2011 ((default-connection)
2012 (with-connection ((default-connection))
2013 (debug-in-emacs condition)))))
2014
2015 (defvar *global-debugger* t
2016 "Non-nil means the Swank debugger hook will be installed globally.")
2017
2018 (add-hook *new-connection-hook* 'install-debugger)
2019 (defun install-debugger (connection)
2020 (declare (ignore connection))
2021 (when *global-debugger*
2022 (install-debugger-globally #'swank-debugger-hook)))
2023
2024 ;;;;; Debugger loop
2025 ;;;
2026 ;;; These variables are dynamically bound during debugging.
2027 ;;;
2028 (defvar *swank-debugger-condition* nil
2029 "The condition being debugged.")
2030
2031 (defvar *sldb-level* 0
2032 "The current level of recursive debugging.")
2033
2034 (defvar *sldb-initial-frames* 20
2035 "The initial number of backtrace frames to send to Emacs.")
2036
2037 (defvar *sldb-restarts* nil
2038 "The list of currenlty active restarts.")
2039
2040 (defvar *sldb-stepping-p* nil
2041 "True during execution of a step command.")
2042
2043 (defun debug-in-emacs (condition)
2044 (let ((*swank-debugger-condition* condition)
2045 (*sldb-restarts* (compute-sane-restarts condition))
2046 (*package* (or (and (boundp '*buffer-package*)
2047 (symbol-value '*buffer-package*))
2048 *package*))
2049 (*sldb-level* (1+ *sldb-level*))
2050 (*sldb-stepping-p* nil)
2051 (*swank-state-stack* (cons :swank-debugger-hook *swank-state-stack*)))
2052 (force-user-output)
2053 (call-with-debugging-environment
2054 (lambda ()
2055 (with-bindings *sldb-printer-bindings*
2056 (sldb-loop *sldb-level*))))))
2057
2058 (defun sldb-loop (level)
2059 (unwind-protect
2060 (catch 'sldb-enter-default-debugger
2061 (send-to-emacs
2062 (list* :debug (current-thread) level
2063 (debugger-info-for-emacs 0 *sldb-initial-frames*)))
2064 (loop (catch 'sldb-loop-catcher
2065 (with-simple-restart (abort "Return to sldb level ~D." level)
2066 (send-to-emacs (list :debug-activate (current-thread)
2067 level))
2068 (handler-bind ((sldb-condition #'handle-sldb-condition))
2069 (read-from-emacs))))))
2070 (send-to-emacs `(:debug-return
2071 ,(current-thread) ,level ,*sldb-stepping-p*))))
2072
2073 (defun handle-sldb-condition (condition)
2074 "Handle an internal debugger condition.
2075 Rather than recursively debug the debugger (a dangerous idea!), these
2076 conditions are simply reported."
2077 (let ((real-condition (original-condition condition)))
2078 (send-to-emacs `(:debug-condition ,(current-thread)
2079 ,(princ-to-string real-condition))))
2080 (throw 'sldb-loop-catcher nil))
2081
2082 (defvar *sldb-condition-printer* #'format-sldb-condition
2083 "Function called to print a condition to an SLDB buffer.")
2084
2085 (defun safe-condition-message (condition)
2086 "Safely print condition to a string, handling any errors during
2087 printing."
2088 (let ((*print-pretty* t) (*print-right-margin* 65))
2089 (handler-case
2090 (funcall *sldb-condition-printer* condition)
2091 (error (cond)
2092 ;; Beware of recursive errors in printing, so only use the condition
2093 ;; if it is printable itself:
2094 (format nil "Unable to display error condition~@[: ~A~]"
2095 (ignore-errors (princ-to-string cond)))))))
2096
2097 (defun debugger-condition-for-emacs ()
2098 (list (safe-condition-message *swank-debugger-condition*)
2099 (format nil " [Condition of type ~S]"
2100 (type-of *swank-debugger-condition*))
2101 (condition-extras *swank-debugger-condition*)))
2102
2103 (defun format-restarts-for-emacs ()
2104 "Return a list of restarts for *swank-debugger-condition* in a
2105 format suitable for Emacs."
2106 (let ((*print-right-margin* most-positive-fixnum))
2107 (loop for restart in *sldb-restarts*
2108 collect (list (princ-to-string (restart-name restart))
2109 (princ-to-string restart)))))
2110
2111
2112 ;;;;; SLDB entry points
2113
2114 (defslimefun sldb-break-with-default-debugger ()
2115 "Invoke the default debugger by returning from our debugger-loop."
2116 (throw 'sldb-enter-default-debugger nil))
2117
2118 (defslimefun backtrace (start end)
2119 "Return a list ((I FRAME) ...) of frames from START to END.
2120 I is an integer describing and FRAME a string."
2121 (loop for frame in (compute-backtrace start end)
2122 for i from start
2123 collect (list i (with-output-to-string (stream)
2124 (handler-case
2125 (with-bindings *backtrace-printer-bindings*
2126 (print-frame frame stream))
2127 (t ()
2128 (format stream "[error printing frame]")))))))
2129
2130 (defslimefun debugger-info-for-emacs (start end)
2131 "Return debugger state, with stack frames from START to END.
2132 The result is a list:
2133 (condition ({restart}*) ({stack-frame}*) (cont*))
2134 where
2135 condition ::= (description type [extra])
2136 restart ::= (name description)
2137 stack-frame ::= (number description)
2138 extra ::= (:references and other random things)
2139 cont ::= continutation
2140 condition---a pair of strings: message, and type. If show-source is
2141 not nil it is a frame number for which the source should be displayed.
2142
2143 restart---a pair of strings: restart name, and description.
2144
2145 stack-frame---a number from zero (the top), and a printed
2146 representation of the frame's call.
2147
2148 continutation---the id of a pending Emacs continuation.
2149
2150 Below is an example return value. In this case the condition was a
2151 division by zero (multi-line description), and only one frame is being
2152 fetched (start=0, end=1).
2153
2154 ((\"Arithmetic error DIVISION-BY-ZERO signalled.
2155 Operation was KERNEL::DIVISION, operands (1 0).\"
2156 \"[Condition of type DIVISION-BY-ZERO]\")
2157 ((\"ABORT\" \"Return to Slime toplevel.\")
2158 (\"ABORT\" \"Return to Top-Level.\"))
2159 ((0 \"(KERNEL::INTEGER-/-INTEGER 1 0)\"))
2160 (4))"
2161 (list (debugger-condition-for-emacs)
2162 (format-restarts-for-emacs)
2163 (backtrace start end)
2164 *pending-continuations*))
2165
2166 (defun nth-restart (index)
2167 (nth index *sldb-restarts*))
2168
2169 (defslimefun invoke-nth-restart (index)
2170 (invoke-restart-interactively (nth-restart index)))
2171
2172 (defslimefun sldb-abort ()
2173 (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))
2174
2175 (defslimefun sldb-continue ()
2176 (continue))
2177
2178 (defslimefun throw-to-toplevel ()
2179 "Invoke the ABORT-REQUEST restart abort an RPC from Emacs.
2180 If we are not evaluating an RPC then ABORT instead."
2181 (let ((restart (find-restart *sldb-quit-restart*)))
2182 (cond (restart (invoke-restart restart))
2183 (t (format nil
2184 "Restart not found: ~a"
2185 *sldb-quit-restart*)))))
2186
2187 (defslimefun invoke-nth-restart-for-emacs (sldb-level n)
2188 "Invoke the Nth available restart.
2189 SLDB-LEVEL is the debug level when the request was made. If this
2190 has changed, ignore the request."
2191 (when (= sldb-level *sldb-level*)
2192 (invoke-nth-restart n)))
2193
2194 (defun wrap-sldb-vars (form)
2195 `(let ((*sldb-level* ,*sldb-level*))
2196 ,form))
2197
2198 (defslimefun eval-string-in-frame (string index)
2199 (to-string (eval-in-frame (wrap-sldb-vars (from-string string))
2200 index)))
2201
2202 (defslimefun pprint-eval-string-in-frame (string index)
2203 (swank-pprint
2204 (multiple-value-list
2205 (eval-in-frame (wrap-sldb-vars (from-string string)) index))))
2206
2207 (defslimefun frame-locals-for-emacs (index)
2208 "Return a property list ((&key NAME ID VALUE) ...) describing
2209 the local variables in the frame INDEX."
2210 (with-bindings *backtrace-printer-bindings*
2211 (mapcar (lambda (frame-locals)
2212 (destructuring-bind (&key name id value) frame-locals
2213 (list :name (prin1-to-string name) :id id
2214 :value (to-string value))))
2215 (frame-locals index))))
2216
2217 (defslimefun frame-catch-tags-for-emacs (frame-index)
2218 (mapcar #'to-string (frame-catch-tags frame-index)))
2219
2220 (defslimefun sldb-disassemble (index)
2221 (with-output-to-string (*standard-output*)
2222 (disassemble-frame index)))
2223
2224 (defslimefun sldb-return-from-frame (index string)
2225 (let ((form (from-string string)))
2226 (to-string (multiple-value-list (return-from-frame index form)))))
2227
2228 (defslimefun sldb-break (name)
2229 (with-buffer-syntax ()
2230 (sldb-break-at-start (read-from-string name))))
2231
2232 (defmacro define-stepper-function (name backend-function-name)
2233 `(defslimefun ,name (frame)
2234 (cond ((sldb-stepper-condition-p *swank-debugger-condition*)
2235 (setq *sldb-stepping-p* t)
2236 (,backend-function-name))
2237 ((find-restart 'continue)
2238 (activate-stepping frame)
2239 (setq *sldb-stepping-p* t)
2240 (continue))
2241 (t
2242 (error "Not currently single-stepping, and no continue restart available.")))))
2243
2244 (define-stepper-function sldb-step sldb-step-into)
2245 (define-stepper-function sldb-next sldb-step-next)
2246 (define-stepper-function sldb-out sldb-step-out)
2247
2248
2249 ;;;; Compilation Commands.
2250
2251 (defstruct (:swank-compilation-unit
2252 (:type list) :named
2253 (:conc-name swank-compilation-unit.)
2254 (:constructor make-swank-compilation-unit ()))
2255 notes ;
2256 results ; a result is of type (MEMBER T NIL :COMPLAINED)
2257 durations ;
2258 )
2259
2260 (defvar *swank-compilation-unit* nil)
2261
2262 (defun measure-time-interval (fn)
2263 "Call FN and return the first return value and the elapsed time.
2264 The time is measured in microseconds."
2265 (declare (type function fn))
2266 (let ((before (get-internal-real-time)))
2267 (values
2268 (funcall fn)
2269 (* (- (get-internal-real-time) before)
2270 (/ 1000000 internal-time-units-per-second)))))
2271
2272 (defun record-note-for-condition (condition)
2273 "Record a note for a compiler-condition into the currently active
2274 Swank-Compilation-Unit."
2275 (push (make-compiler-note condition)
2276 (swank-compilation-unit.notes *swank-compilation-unit*)))
2277
2278 (defun make-compiler-note (condition)
2279 "Make a compiler note data structure from a compiler-condition."
2280 (declare (type compiler-condition condition))
2281 (list* :message (message condition)
2282 :severity (severity condition)
2283 :location (location condition)
2284 :references (references condition)
2285 (let ((s (short-message condition)))
2286 (if s (list :short-message s)))))
2287
2288 (defmacro with-swank-compilation-unit ((&key override) &body body)
2289 "Similiar to CL:WITH-COMPILATION-UNIT. Within a
2290 Swank-Compilation-Unit all notes, results etc. produced by
2291 COMPILE-FILE-FOR-EMACS and COMPILE-STRING-FOR-EMACS (possibly called
2292 more than once) will be collected into this unit."
2293 (if override
2294 `(let ((*swank-compilation-unit* (make-swank-compilation-unit)))
2295 ,@body)
2296 `(let ((*swank-compilation-unit* (or *swank-compilation-unit*
2297 (make-swank-compilation-unit))))
2298 ,@body)))
2299
2300 (defun swank-compilation-unit-for-emacs (unit)
2301 "Make a Swank-Compilation-Unit suitable for Emacs."
2302 (let ((new (make-swank-compilation-unit)))
2303 (with-struct (swank-compilation-unit. notes results durations) unit
2304 (setf (swank-compilation-unit.notes new) (reverse notes))
2305 (setf (swank-compilation-unit.results new) (reverse results))
2306 (setf (swank-compilation-unit.durations new)
2307 (reverse (mapcar #'(lambda (usecs) (/ usecs 1000000.0)) durations))))
2308 new))
2309
2310 (defun swank-compiler (function)
2311 (let ((notes-p))
2312 (multiple-value-bind (result usecs)
2313 (with-simple-restart (abort "Abort SLIME compilation.")
2314 (handler-bind ((compiler-condition #'(lambda (c)
2315 (setf notes-p t)
2316 (record-note-for-condition c))))
2317 (measure-time-interval function)))
2318 (when result (setf result (if notes-p :complained t)))
2319 (when (eql usecs t) (setf usecs 0)) ; compilation aborted.
2320 (push result (swank-compilation-unit.results *swank-compilation-unit*))
2321 (push usecs (swank-compilation-unit.durations *swank-compilation-unit*))
2322 (swank-compilation-unit-for-emacs *swank-compilation-unit*))))
2323
2324 (defslimefun compile-file-for-emacs (filename load-p)
2325 "Compile FILENAME and, when LOAD-P, load the result.
2326 Record compiler notes signalled as `compiler-condition's."
2327 (with-swank-compilation-unit (:override nil)
2328 (with-buffer-syntax ()
2329 (let ((*compile-print* nil))
2330 (swank-compiler
2331 (lambda ()
2332 (swank-compile-file filename load-p
2333 (or (guess-external-format filename)
2334 :default))))))))
2335
2336 (defslimefun compile-string-for-emacs (string buffer position directory debug)
2337 "Compile STRING (exerpted from BUFFER at POSITION).
2338 Record compiler notes signalled as `compiler-condition's."
2339 (with-swank-compilation-unit (:override nil)
2340 (with-buffer-syntax ()
2341 (swank-compiler
2342 (lambda ()
2343 (let ((*compile-print* nil) (*compile-verbose* t))
2344 (swank-compile-string string :buffer buffer :position position
2345 :directory directory
2346 :debug debug)))))))
2347
2348
2349 (defun file-newer-p (new-file old-file)
2350 "Returns true if NEW-FILE is newer than OLD-FILE."
2351 (> (file-write-date new-file) (file-write-date old-file)))
2352
2353 (defun requires-compile-p (source-file)
2354 (let ((fasl-file (probe-file (compile-file-pathname source-file))))
2355 (or (not fasl-file)
2356 (file-newer-p source-file fasl-file))))
2357
2358 (defslimefun compile-file-if-needed (filename loadp)
2359 (cond ((requires-compile-p filename)
2360 (compile-file-for-emacs filename loadp))
2361 (loadp
2362 (load (compile-file-pathname filename))
2363 nil)))
2364
2365
2366 ;;;; Loading
2367
2368 (defslimefun load-file (filename)
2369 (to-string (load filename)))
2370
2371
2372 ;;;;; swank-require
2373
2374 (defslimefun swank-require (modules &optional filename)
2375 "Load the module MODULE."
2376 (dolist (module (if (listp modules) modules (list modules)))
2377 (unless (member (string module) *modules* :test #'string=)
2378 (require module (or filename (module-filename module)))))
2379 *modules*)
2380
2381 (defvar *find-module* 'find-module
2382 "Pluggable function to locate modules.
2383 The function receives a module name as argument and should return
2384 the filename of the module (or nil if the file doesn't exist).")
2385
2386 (defun module-filename (module)
2387 "Return the filename for the module MODULE."
2388 (or (funcall *find-module* module)
2389 (error "Can't locate module: ~s" module)))
2390
2391 ;;;;;; Simple *find-module* function.
2392
2393 (defun merged-directory (dirname defaults)
2394 (pathname-directory
2395 (merge-pathnames
2396 (make-pathname :directory `(:relative ,dirname) :defaults defaults)
2397 defaults)))
2398
2399 (defvar *load-path* '()
2400 "A list of directories to search for modules.")
2401
2402 (defun module-canditates (name dir)
2403 (list (compile-file-pathname (make-pathname :name name :defaults dir))
2404 (make-pathname :name name :type "lisp" :defaults dir)))
2405
2406 (defun find-module (module)
2407 (let ((name (string-downcase module)))
2408 (some (lambda (dir) (some #'probe-file (module-canditates name dir)))
2409 *load-path*)))
2410
2411
2412 ;;;; Macroexpansion
2413
2414 (defvar *macroexpand-printer-bindings*
2415 '((*print-circle* . nil)
2416 (*print-pretty* . t)
2417 (*print-escape* . t)
2418 (*print-lines* . nil)
2419 (*print-level* . nil)
2420 (*print-length* . nil)))
2421
2422 (defun apply-macro-expander (expander string)
2423 (with-buffer-syntax ()
2424 (with-bindings *macroexpand-printer-bindings*
2425 (prin1-to-string (funcall expander (from-string string))))))
2426
2427 (defslimefun swank-macroexpand-1 (string)
2428 (apply-macro-expander #'macroexpand-1 string))
2429
2430 (defslimefun swank-macroexpand (string)
2431 (apply-macro-expander #'macroexpand string))
2432
2433 (defslimefun swank-macroexpand-all (string)
2434 (apply-macro-expander #'macroexpand-all string))
2435
2436 (defslimefun swank-compiler-macroexpand-1 (string)
2437 (apply-macro-expander #'compiler-macroexpand-1 string))
2438
2439 (defslimefun swank-compiler-macroexpand (string)
2440 (apply-macro-expander #'compiler-macroexpand string))
2441
2442 (defslimefun disassemble-symbol (name)
2443 (with-buffer-syntax ()
2444 (with-output-to-string (*standard-output*)
2445 (let ((*print-readably* nil))
2446 (disassemble (fdefinition (from-string name)))))))
2447
2448
2449 ;;;; Simple completion
2450
2451 (defslimefun simple-completions (string package)
2452 "Return a list of completions for the string STRING."
2453 (let ((strings (all-completions string package #'prefix-match-p)))
2454 (list strings (longest-common-prefix strings))))
2455
2456 (defun all-completions (string package test)
2457 (multiple-value-bind (name pname intern) (tokenize-symbol string)
2458 (let* ((extern (and pname (not intern)))
2459 (pack (cond ((equal pname "") keyword-package)
2460 ((not pname) (guess-buffer-package package))
2461 (t (guess-package pname))))
2462 (test (lambda (sym) (funcall test name (unparse-symbol sym))))
2463 (syms (and pack (matching-symbols pack extern test))))
2464 (format-completion-set (mapcar #'unparse-symbol syms) intern pname))))
2465
2466 (defun matching-symbols (package external test)
2467 (let ((test (if external
2468 (lambda (s)
2469 (and (symbol-external-p s package)
2470 (funcall test s)))
2471 test))
2472 (result '()))
2473 (do-symbols (s package)
2474 (when (funcall test s)
2475 (push s result)))
2476 (remove-duplicates result)))
2477
2478 (defun unparse-symbol (symbol)
2479 (let ((*print-case* (case (readtable-case *readtable*)
2480 (:downcase :upcase)
2481 (t :downcase))))
2482 (unparse-name (symbol-name symbol))))
2483
2484 (defun prefix-match-p (prefix string)
2485 "Return true if PREFIX is a prefix of STRING."
2486 (not (mismatch prefix string :end2 (min (length string) (length prefix)))))
2487
2488 (defun longest-common-prefix (strings)
2489 "Return the longest string that is a common prefix of STRINGS."
2490 (if (null strings)
2491 ""
2492 (flet ((common-prefix (s1 s2)
2493 (let ((diff-pos (mismatch s1 s2)))
2494 (if diff-pos (subseq s1 0 diff-pos) s1))))
2495 (reduce #'common-prefix strings))))
2496
2497 (defun format-completion-set (strings internal-p package-name)
2498 "Format a set of completion strings.
2499 Returns a list of completions with package qualifiers if needed."
2500 (mapcar (lambda (string) (untokenize-symbol package-name internal-p string))
2501 (sort strings #'string<)))
2502
2503
2504 ;;;; Simple arglist display
2505
2506 (defslimefun operator-arglist (name package)
2507 (ignore-errors
2508 (let ((args (arglist (parse-symbol name (guess-buffer-package package))))
2509 (*print-escape* nil))
2510 (cond ((eq args :not-available) nil)
2511 (t (format nil "(~a ~/pprint-fill/)" name args))))))
2512
2513
2514 ;;;; Documentation
2515
2516 (defslimefun apropos-list-for-emacs (name &optional external-only
2517 case-sensitive package)
2518 "Make an apropos search for Emacs.
2519 The result is a list of property lists."
2520 (let ((package (if package
2521 (or (parse-package package)
2522 (error "No such package: ~S" package)))))
2523 ;; The MAPCAN will filter all uninteresting symbols, i.e. those
2524 ;; who cannot be meaningfully described.
2525 (mapcan (listify #'briefly-describe-symbol-for-emacs)
2526 (sort (remove-duplicates
2527 (apropos-symbols name external-only case-sensitive package))
2528 #'present-symbol-before-p))))
2529
2530 (defun briefly-describe-symbol-for-emacs (symbol)
2531 "Return a property list describing SYMBOL.
2532 Like `describe-symbol-for-emacs' but with at most one line per item."
2533 (flet ((first-line (string)
2534 (let ((pos (position #\newline string)))
2535 (if (null pos) string (subseq string 0 pos)))))
2536 (let ((desc (map-if #'stringp #'first-line
2537 (describe-symbol-for-emacs symbol))))
2538 (if desc
2539 (list* :designator (to-string symbol) desc)))))
2540
2541 (defun map-if (test fn &rest lists)
2542 "Like (mapcar FN . LISTS) but only call FN on objects satisfying TEST.
2543 Example:
2544 \(map-if #'oddp #'- '(1 2 3 4 5)) => (-1 2 -3 4 -5)"
2545 (apply #'mapcar
2546 (lambda (x) (if (funcall test x) (funcall fn x) x))
2547 lists))
2548
2549 (defun listify (f)
2550 "Return a function like F, but which returns any non-null value
2551 wrapped in a list."
2552 (lambda (x)
2553 (let ((y (funcall f x)))
2554 (and y (list y)))))
2555
2556 (defun present-symbol-before-p (x y)
2557 "Return true if X belongs before Y in a printed summary of symbols.
2558 Sorted alphabetically by package name and then symbol name, except
2559 that symbols accessible in the current package go first."
2560 (declare (type symbol x y))
2561 (flet ((accessible (s)
2562 ;; Test breaks on NIL for package that does not inherit it
2563 (eq (find-symbol (symbol-name s) *buffer-package*) s)))
2564 (let ((ax (accessible x)) (ay (accessible y)))
2565 (cond ((and ax ay) (string< (symbol-name x) (symbol-name y)))
2566 (ax t)
2567 (ay nil)
2568 (t (let ((px (symbol-package x)) (py (symbol-package y)))
2569 (if (eq px py)
2570 (string< (symbol-name x) (symbol-name y))
2571 (string< (package-name px) (package-name py)))))))))
2572
2573 (defun make-apropos-matcher (pattern case-sensitive)
2574 (let ((chr= (if case-sensitive #'char= #'char-equal)))
2575 (lambda (symbol)
2576 (search pattern (string symbol) :test chr=))))
2577
2578 (defun apropos-symbols (string external-only case-sensitive package)
2579 (let ((packages (or package (remove (find-package :keyword)
2580 (list-all-packages))))
2581 (matcher (make-apropos-matcher string case-sensitive))
2582 (result))
2583 (with-package-iterator (next packages :external :internal)
2584 (loop (multiple-value-bind (morep symbol) (next)
2585 (cond ((not morep) (return))
2586 ((and (if external-only (symbol-external-p symbol) t)
2587 (funcall matcher symbol))
2588 (push symbol result))))))
2589 result))
2590
2591 (defun call-with-describe-settings (fn)
2592 (let ((*print-readably* nil))
2593 (funcall fn)))
2594
2595 (defmacro with-describe-settings ((&rest _) &body body)
2596 (declare (ignore _))
2597 `(call-with-describe-settings (lambda () ,@body)))
2598
2599 (defun describe-to-string (object)
2600 (with-describe-settings ()
2601 (with-output-to-string (*standard-output*)
2602 (describe object))))
2603
2604 (defslimefun describe-symbol (symbol-name)
2605 (with-buffer-syntax ()
2606 (describe-to-string (parse-symbol-or-lose symbol-name))))
2607
2608 (defslimefun describe-function (name)
2609 (with-buffer-syntax ()
2610 (let ((symbol (parse-symbol-or-lose name)))
2611 (describe-to-string (or (macro-function symbol)
2612 (symbol-function symbol))))))
2613
2614 (defslimefun describe-definition-for-emacs (name kind)
2615 (with-buffer-syntax ()
2616 (with-describe-settings ()
2617 (with-output-to-string (*standard-output*)
2618 (describe-definition (parse-symbol-or-lose name) kind)))))
2619
2620 (defslimefun documentation-symbol (symbol-name &optional default)
2621 (with-buffer-syntax ()
2622 (multiple-value-bind (sym foundp) (parse-symbol symbol-name)
2623 (if foundp
2624 (let ((vdoc (documentation sym 'variable))
2625 (fdoc (documentation sym 'function)))
2626 (or (and (or vdoc fdoc)
2627 (concatenate 'string
2628 fdoc
2629 (and vdoc fdoc '(#\Newline #\Newline))
2630 vdoc))
2631 default))
2632 default))))
2633
2634
2635 ;;;; Package Commands
2636
2637 (defslimefun list-all-package-names (&optional nicknames)
2638 "Return a list of all package names.
2639 Include the nicknames if NICKNAMES is true."
2640 (mapcar #'unparse-name
2641 (if nicknames
2642 (mapcan #'package-names (list-all-packages))
2643 (mapcar #'package-name (list-all-packages)))))
2644
2645
2646 ;;;; Tracing
2647
2648 ;; Use eval for the sake of portability...
2649 (defun tracedp (fspec)
2650 (member fspec (eval '(trace))))
2651
2652 (defslimefun swank-toggle-trace (spec-string)
2653 (let ((spec (from-string spec-string)))
2654 (cond ((consp spec) ; handle complicated cases in the backend
2655 (toggle-trace spec))
2656 ((tracedp spec)
2657 (eval `(untrace ,spec))
2658 (format nil "~S is now untraced." spec))
2659 (t
2660 (eval `(trace ,spec))
2661 (format nil "~S is now traced." spec)))))
2662
2663 (defslimefun untrace-all ()
2664 (untrace))
2665
2666 (defslimefun redirect-trace-output (target)
2667 (setf (connection.trace-output *emacs-connection*)
2668 (make-output-stream-for-target *emacs-connection* target))
2669 nil)
2670
2671
2672 ;;;; Undefing
2673
2674 (defslimefun undefine-function (fname-string)
2675 (let ((fname (from-string fname-string)))
2676 (format nil "~S" (fmakunbound fname))))
2677
2678
2679 ;;;; Profiling
2680
2681 (defun profiledp (fspec)
2682 (member fspec (profiled-functions)))
2683
2684 (defslimefun toggle-profile-fdefinition (fname-string)
2685 (let ((fname (from-string fname-string)))
2686 (cond ((profiledp fname)
2687 (unprofile fname)
2688 (format nil "~S is now unprofiled." fname))
2689 (t
2690 (profile fname)
2691 (format nil "~S is now profiled." fname)))))
2692
2693
2694 ;;;; Source Locations
2695
2696 (defslimefun find-definition-for-thing (thing)
2697 (find-source-location thing))
2698
2699 (defslimefun find-definitions-for-emacs (name)
2700 "Return a list ((DSPEC LOCATION) ...) of definitions for NAME.
2701 DSPEC is a string and LOCATION a source location. NAME is a string."
2702 (multiple-value-bind (sexp error) (ignore-errors (values (from-string name)))
2703 (unless error
2704 (mapcar #'xref>elisp (find-definitions sexp)))))
2705
2706 (defslimefun xref (type name)
2707 (let ((symbol (parse-symbol-or-lose name *buffer-package*)))
2708 (mapcar #'xref>elisp
2709 (ecase type
2710 (:calls (who-calls symbol))
2711 (:calls-who (calls-who symbol))
2712 (:references (who-references symbol))
2713 (:binds (who-binds symbol))
2714 (:sets (who-sets symbol))
2715 (:macroexpands (who-macroexpands symbol))
2716 (:specializes (who-specializes symbol))
2717 (:callers (list-callers symbol))
2718 (:callees (list-callees symbol))))))
2719
2720 (defun xref>elisp (xref)
2721 (destructuring-bind (name loc) xref
2722 (list (to-string name) loc)))
2723
2724
2725 ;;;; Inspecting
2726
2727 (defvar *inspectee*)
2728 (defvar *inspectee-content*)
2729 (defvar *inspectee-parts*)
2730 (defvar *inspectee-actions*)
2731 (defvar *inspector-stack*)
2732 (defvar *inspector-history*)
2733
2734 (defun reset-inspector ()
2735 (setq *inspectee* nil
2736 *inspectee-content* nil
2737 *inspectee-parts* (make-array 10 :adjustable t :fill-pointer 0)
2738 *inspectee-actions* (make-array 10 :adjustable t :fill-pointer 0)
2739 *inspector-stack* '()
2740 *inspector-history* (make-array 10 :adjustable t :fill-pointer 0)))
2741
2742 (defslimefun init-inspector (string)
2743 (with-buffer-syntax ()
2744 (reset-inspector)
2745 (inspect-object (eval (read-from-string string)))))
2746