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

Contents of /slime/swank.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.355 - (show annotations)
Tue Dec 20 00:26:25 2005 UTC (8 years, 4 months ago) by mbaringer
Branch: MAIN
Changes since 1.354: +33 -25 lines
(all-slots-for-inspector): New function.
(inspect-for-emacs): Use all-slots-for-inspector.
1 ;;; -*- outline-regexp: ";;;;;*"; indent-tabs-mode: nil -*-
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 :common-lisp :swank-backend)
17 (:export #:startup-multiprocessing
18 #:start-server
19 #:create-swank-server
20 #:create-server
21 #:ed-in-emacs
22 #:print-indentation-lossage
23 #:swank-debugger-hook
24 ;; These are user-configurable variables:
25 #:*communication-style*
26 #:*log-events*
27 #:*log-output*
28 #:*use-dedicated-output-stream*
29 #:*dedicated-output-stream-port*
30 #:*configure-emacs-indentation*
31 #:*readtable-alist*
32 #:*globally-redirect-io*
33 #:*global-debugger*
34 #:*sldb-printer-bindings*
35 #:*swank-pprint-bindings*
36 #:*default-worker-thread-bindings*
37 #:*macroexpand-printer-bindings*
38 #:*record-repl-results*
39 ;; These are re-exported directly from the backend:
40 #:buffer-first-change
41 #:frame-source-location-for-emacs
42 #:restart-frame
43 #:sldb-step
44 #:sldb-break
45 #:sldb-break-on-return
46 #:profiled-functions
47 #:profile-report
48 #:profile-reset
49 #:unprofile-all
50 #:profile-package
51 #:default-directory
52 #:set-default-directory
53 #:quit-lisp))
54
55 (in-package :swank)
56
57
58 ;;;; Top-level variables, constants, macros
59
60 (defconstant cl-package (find-package :cl)
61 "The COMMON-LISP package.")
62
63 (defconstant keyword-package (find-package :keyword)
64 "The KEYWORD package.")
65
66 (defvar *canonical-package-nicknames*
67 `((:common-lisp-user . :cl-user))
68 "Canonical package names to use instead of shortest name/nickname.")
69
70 (defvar *auto-abbreviate-dotted-packages* t
71 "Abbreviate dotted package names to their last component if T.")
72
73 (defvar *swank-io-package*
74 (let ((package (make-package :swank-io-package :use '())))
75 (import '(nil t quote) package)
76 package))
77
78 (defconstant default-server-port 4005
79 "The default TCP port for the server (when started manually).")
80
81 (defvar *swank-debug-p* t
82 "When true, print extra debugging information.")
83
84 (defvar *redirect-io* t
85 "When non-nil redirect Lisp standard I/O to Emacs.
86 Redirection is done while Lisp is processing a request for Emacs.")
87
88 (defvar *sldb-printer-bindings*
89 `((*print-pretty* . nil)
90 (*print-level* . 4)
91 (*print-length* . 10)
92 (*print-circle* . t)
93 (*print-readably* . nil)
94 (*print-pprint-dispatch* . ,(copy-pprint-dispatch nil))
95 (*print-gensym* . t)
96 (*print-base* . 10)
97 (*print-radix* . nil)
98 (*print-array* . t)
99 (*print-lines* . 200)
100 (*print-escape* . t))
101 "A set of printer variables used in the debugger.")
102
103 (defvar *default-worker-thread-bindings* '()
104 "An alist to initialize dynamic variables in worker threads.
105 The list has the form ((VAR . VALUE) ...). Each variable VAR will be
106 bound to the corresponding VALUE.")
107
108 (defun call-with-bindings (alist fun)
109 "Call FUN with variables bound according to ALIST.
110 ALIST is a list of the form ((VAR . VAL) ...)."
111 (let* ((rlist (reverse alist))
112 (vars (mapcar #'car rlist))
113 (vals (mapcar #'cdr rlist)))
114 (progv vars vals
115 (funcall fun))))
116
117 (defmacro with-bindings (alist &body body)
118 "See `call-with-bindings'."
119 `(call-with-bindings ,alist (lambda () ,@body)))
120
121 ;;; The `DEFSLIMEFUN' macro defines a function that Emacs can call via
122 ;;; RPC.
123
124 (defmacro defslimefun (name arglist &body rest)
125 "A DEFUN for functions that Emacs can call by RPC."
126 `(progn
127 (defun ,name ,arglist ,@rest)
128 ;; see <http://www.franz.com/support/documentation/6.2/doc/pages/variables/compiler/s_cltl1-compile-file-toplevel-compatibility-p_s.htm>
129 (eval-when (:compile-toplevel :load-toplevel :execute)
130 (export ',name :swank))))
131
132 (declaim (ftype (function () nil) missing-arg))
133 (defun missing-arg ()
134 "A function that the compiler knows will never to return a value.
135 You can use (MISSING-ARG) as the initform for defstruct slots that
136 must always be supplied. This way the :TYPE slot option need not
137 include some arbitrary initial value like NIL."
138 (error "A required &KEY or &OPTIONAL argument was not supplied."))
139
140
141 ;;;; Hooks
142 ;;;
143 ;;; We use Emacs-like `add-hook' and `run-hook' utilities to support
144 ;;; simple indirection. The interface is more CLish than the Emacs
145 ;;; Lisp one.
146
147 (defmacro add-hook (place function)
148 "Add FUNCTION to the list of values on PLACE."
149 `(pushnew ,function ,place))
150
151 (defun run-hook (functions &rest arguments)
152 "Call each of FUNCTIONS with ARGUMENTS."
153 (dolist (function functions)
154 (apply function arguments)))
155
156 (defvar *new-connection-hook* '()
157 "This hook is run each time a connection is established.
158 The connection structure is given as the argument.
159 Backend code should treat the connection structure as opaque.")
160
161 (defvar *connection-closed-hook* '()
162 "This hook is run when a connection is closed.
163 The connection as passed as an argument.
164 Backend code should treat the connection structure as opaque.")
165
166 (defvar *pre-reply-hook* '()
167 "Hook run (without arguments) immediately before replying to an RPC.")
168
169
170 ;;;; Connections
171 ;;;
172 ;;; Connection structures represent the network connections between
173 ;;; Emacs and Lisp. Each has a socket stream, a set of user I/O
174 ;;; streams that redirect to Emacs, and optionally a second socket
175 ;;; used solely to pipe user-output to Emacs (an optimization).
176 ;;;
177
178 (defvar *coding-system* ':iso-latin-1-unix)
179
180 (defstruct (connection
181 (:conc-name connection.)
182 (:print-function print-connection))
183 ;; Raw I/O stream of socket connection.
184 (socket-io (missing-arg) :type stream :read-only t)
185 ;; Optional dedicated output socket (backending `user-output' slot).
186 ;; Has a slot so that it can be closed with the connection.
187 (dedicated-output nil :type (or stream null))
188 ;; Streams that can be used for user interaction, with requests
189 ;; redirected to Emacs.
190 (user-input nil :type (or stream null))
191 (user-output nil :type (or stream null))
192 (user-io nil :type (or stream null))
193 ;; In multithreaded systems we delegate certain tasks to specific
194 ;; threads. The `reader-thread' is responsible for reading network
195 ;; requests from Emacs and sending them to the `control-thread'; the
196 ;; `control-thread' is responsible for dispatching requests to the
197 ;; threads that should handle them; the `repl-thread' is the one
198 ;; that evaluates REPL expressions. The control thread dispatches
199 ;; all REPL evaluations to the REPL thread and for other requests it
200 ;; spawns new threads.
201 reader-thread
202 control-thread
203 repl-thread
204 ;; Callback functions:
205 ;; (SERVE-REQUESTS <this-connection>) serves all pending requests
206 ;; from Emacs.
207 (serve-requests (missing-arg) :type function)
208 ;; (READ) is called to read and return one message from Emacs.
209 (read (missing-arg) :type function)
210 ;; (SEND OBJECT) is called to send one message to Emacs.
211 (send (missing-arg) :type function)
212 ;; (CLEANUP <this-connection>) is called when the connection is
213 ;; closed.
214 (cleanup nil :type (or null function))
215 ;; Cache of macro-indentation information that has been sent to Emacs.
216 ;; This is used for preparing deltas to update Emacs's knowledge.
217 ;; Maps: symbol -> indentation-specification
218 (indentation-cache (make-hash-table :test 'eq) :type hash-table)
219 ;; The list of packages represented in the cache:
220 (indentation-cache-packages '())
221 ;; The communication style used.
222 (communication-style nil :type (member nil :spawn :sigio :fd-handler))
223 ;; The coding system for network streams.
224 (external-format *coding-system* :type (member :iso-latin-1-unix
225 :emacs-mule-unix
226 :utf-8-unix
227 :euc-jp-unix)))
228
229 (defun print-connection (conn stream depth)
230 (declare (ignore depth))
231 (print-unreadable-object (conn stream :type t :identity t)))
232
233 (defvar *connections* '()
234 "List of all active connections, with the most recent at the front.")
235
236 (defvar *emacs-connection* nil
237 "The connection to Emacs currently in use.")
238
239 (defvar *swank-state-stack* '()
240 "A list of symbols describing the current state. Used for debugging
241 and to detect situations where interrupts can be ignored.")
242
243 (defun default-connection ()
244 "Return the 'default' Emacs connection.
245 This connection can be used to talk with Emacs when no specific
246 connection is in use, i.e. *EMACS-CONNECTION* is NIL.
247
248 The default connection is defined (quite arbitrarily) as the most
249 recently established one."
250 (first *connections*))
251
252 (defslimefun state-stack ()
253 "Return the value of *SWANK-STATE-STACK*."
254 *swank-state-stack*)
255
256 (define-condition slime-protocol-error (error)
257 ((condition :initarg :condition :reader slime-protocol-error.condition))
258 (:report (lambda (condition stream)
259 (format stream "~A" (slime-protocol-error.condition condition)))))
260
261 (add-hook *new-connection-hook* 'notify-backend-of-connection)
262 (defun notify-backend-of-connection (connection)
263 (declare (ignore connection))
264 (emacs-connected))
265
266
267 ;;;; Helper macros
268
269 (defmacro with-io-redirection ((connection) &body body)
270 "Execute BODY I/O redirection to CONNECTION.
271 If *REDIRECT-IO* is true then all standard I/O streams are redirected."
272 `(maybe-call-with-io-redirection ,connection (lambda () ,@body)))
273
274 (defun maybe-call-with-io-redirection (connection fun)
275 (if *redirect-io*
276 (call-with-redirected-io connection fun)
277 (funcall fun)))
278
279 (defmacro with-connection ((connection) &body body)
280 "Execute BODY in the context of CONNECTION."
281 `(call-with-connection ,connection (lambda () ,@body)))
282
283 (defun call-with-connection (connection fun)
284 (let ((*emacs-connection* connection))
285 (with-io-redirection (*emacs-connection*)
286 (let ((*debugger-hook* #'swank-debugger-hook))
287 (funcall fun)))))
288
289 (defmacro without-interrupts (&body body)
290 `(call-without-interrupts (lambda () ,@body)))
291
292 (defmacro destructure-case (value &rest patterns)
293 "Dispatch VALUE to one of PATTERNS.
294 A cross between `case' and `destructuring-bind'.
295 The pattern syntax is:
296 ((HEAD . ARGS) . BODY)
297 The list of patterns is searched for a HEAD `eq' to the car of
298 VALUE. If one is found, the BODY is executed with ARGS bound to the
299 corresponding values in the CDR of VALUE."
300 (let ((operator (gensym "op-"))
301 (operands (gensym "rand-"))
302 (tmp (gensym "tmp-")))
303 `(let* ((,tmp ,value)
304 (,operator (car ,tmp))
305 (,operands (cdr ,tmp)))
306 (case ,operator
307 ,@(loop for (pattern . body) in patterns collect
308 (if (eq pattern t)
309 `(t ,@body)
310 (destructuring-bind (op &rest rands) pattern
311 `(,op (destructuring-bind ,rands ,operands
312 ,@body)))))
313 ,@(if (eq (caar (last patterns)) t)
314 '()
315 `((t (error "destructure-case failed: ~S" ,tmp))))))))
316
317 (defmacro with-temp-package (var &body body)
318 "Execute BODY with VAR bound to a temporary package.
319 The package is deleted before returning."
320 `(let ((,var (make-package (gensym "TEMP-PACKAGE-"))))
321 (unwind-protect (progn ,@body)
322 (delete-package ,var))))
323
324 (defvar *log-events* nil)
325 (defvar *log-output* *error-output*)
326
327 (defun log-event (format-string &rest args)
328 "Write a message to *terminal-io* when *log-events* is non-nil.
329 Useful for low level debugging."
330 (when *log-events*
331 (apply #'format *log-output* format-string args)
332 (force-output *log-output*)))
333
334
335 ;;;; TCP Server
336
337 (defvar *use-dedicated-output-stream* t
338 "When T swank will attempt to create a second connection to
339 Emacs which is used just to send output.")
340
341 (defvar *dedicated-output-stream-port* 0
342 "Which port we should use for the dedicated output stream.")
343
344 (defvar *communication-style* (preferred-communication-style))
345
346 (defvar *dedicated-output-stream-buffering*
347 (if (eq *communication-style* :spawn) :full :none)
348 "The buffering scheme that should be used for the output stream.
349 Valid values are :none, :line, and :full.")
350
351 (defun start-server (port-file &key (style *communication-style*)
352 dont-close (external-format *coding-system*))
353 "Start the server and write the listen port number to PORT-FILE.
354 This is the entry point for Emacs."
355 (when (eq style :spawn)
356 (initialize-multiprocessing))
357 (setup-server 0 (lambda (port) (announce-server-port port-file port))
358 style dont-close external-format)
359 (when (eq style :spawn)
360 (startup-idle-and-top-level-loops)))
361
362 (defun create-server (&key (port default-server-port)
363 (style *communication-style*)
364 dont-close (external-format *coding-system*))
365 "Start a SWANK server on PORT running in STYLE.
366 If DONT-CLOSE is true then the listen socket will accept multiple
367 connections, otherwise it will be closed after the first."
368 (setup-server port #'simple-announce-function style dont-close
369 external-format))
370
371 (defun create-swank-server (&optional (port default-server-port)
372 (style *communication-style*)
373 (announce-fn #'simple-announce-function)
374 dont-close (external-format *coding-system*))
375 (setup-server port announce-fn style dont-close external-format))
376
377 (defparameter *loopback-interface* "127.0.0.1")
378
379 (defun setup-server (port announce-fn style dont-close external-format)
380 (declare (type function announce-fn))
381 (let* ((socket (create-socket *loopback-interface* port))
382 (port (local-port socket)))
383 (funcall announce-fn port)
384 (flet ((serve ()
385 (serve-connection socket style dont-close external-format)))
386 (ecase style
387 (:spawn
388 (spawn (lambda () (loop do (serve) while dont-close))
389 :name "Swank"))
390 ((:fd-handler :sigio)
391 (add-fd-handler socket (lambda () (serve))))
392 ((nil) (loop do (serve) while dont-close)))
393 port)))
394
395 (defun serve-connection (socket style dont-close external-format)
396 (let ((client (accept-authenticated-connection
397 socket :external-format external-format)))
398 (unless dont-close
399 (close-socket socket))
400 (let ((connection (create-connection client style external-format)))
401 (run-hook *new-connection-hook* connection)
402 (push connection *connections*)
403 (serve-requests connection))))
404
405 (defun accept-authenticated-connection (&rest args)
406 (let ((new (apply #'accept-connection args))
407 (secret (slime-secret)))
408 (when secret
409 (let ((first-val (decode-message new)))
410 (unless (and (stringp first-val) (string= first-val secret))
411 (close new)
412 (error "Incoming connection doesn't know the password."))))
413 new))
414
415 (defun slime-secret ()
416 "Finds the magic secret from the user's home directory. Returns nil
417 if the file doesn't exist; otherwise the first line of the file."
418 (with-open-file (in
419 (merge-pathnames (user-homedir-pathname) #p".slime-secret")
420 :if-does-not-exist nil)
421 (and in (read-line in nil ""))))
422
423 (defun serve-requests (connection)
424 "Read and process all requests on connections."
425 (funcall (connection.serve-requests connection) connection))
426
427 (defun announce-server-port (file port)
428 (with-open-file (s file
429 :direction :output
430 :if-exists :error
431 :if-does-not-exist :create)
432 (format s "~S~%" port))
433 (simple-announce-function port))
434
435 (defun simple-announce-function (port)
436 (when *swank-debug-p*
437 (format *debug-io* "~&;; Swank started at port: ~D.~%" port)
438 (force-output *debug-io*)))
439
440 (defun open-streams (connection)
441 "Return the 4 streams for IO redirection:
442 DEDICATED-OUTPUT INPUT OUTPUT IO"
443 (multiple-value-bind (output-fn dedicated-output)
444 (make-output-function connection)
445 (let ((input-fn
446 (lambda ()
447 (with-connection (connection)
448 (with-simple-restart (abort-read
449 "Abort reading input from Emacs.")
450 (read-user-input-from-emacs))))))
451 (multiple-value-bind (in out) (make-fn-streams input-fn output-fn)
452 (let ((out (or dedicated-output out)))
453 (let ((io (make-two-way-stream in out)))
454 (mapc #'make-stream-interactive (list in out io))
455 (values dedicated-output in out io)))))))
456
457 (defun make-output-function (connection)
458 "Create function to send user output to Emacs.
459 This function may open a dedicated socket to send output. It
460 returns two values: the output function, and the dedicated
461 stream (or NIL if none was created)."
462 (if *use-dedicated-output-stream*
463 (let ((stream (open-dedicated-output-stream
464 (connection.socket-io connection)
465 (connection.external-format connection))))
466 (values (lambda (string)
467 (write-string string stream)
468 (force-output stream))
469 stream))
470 (values (lambda (string)
471 (with-connection (connection)
472 (with-simple-restart
473 (abort "Abort sending output to Emacs.")
474 (send-to-emacs `(:write-string ,string)))))
475 nil)))
476
477 (defun open-dedicated-output-stream (socket-io external-format)
478 "Open a dedicated output connection to the Emacs on SOCKET-IO.
479 Return an output stream suitable for writing program output.
480
481 This is an optimized way for Lisp to deliver output to Emacs."
482 (let* ((socket (create-socket *loopback-interface*
483 *dedicated-output-stream-port*))
484 (port (local-port socket)))
485 (encode-message `(:open-dedicated-output-stream ,port) socket-io)
486 (accept-authenticated-connection
487 socket :external-format external-format
488 :buffering *dedicated-output-stream-buffering*)))
489
490 (defun handle-request (connection)
491 "Read and process one request. The processing is done in the extend
492 of the toplevel restart."
493 (assert (null *swank-state-stack*))
494 (let ((*swank-state-stack* '(:handle-request))
495 (*debugger-hook* nil))
496 (with-connection (connection)
497 (with-simple-restart (abort-request "Abort handling SLIME request.")
498 (read-from-emacs)))))
499
500 (defun current-socket-io ()
501 (connection.socket-io *emacs-connection*))
502
503 (defun close-connection (c &optional condition)
504 (let ((cleanup (connection.cleanup c)))
505 (when cleanup
506 (funcall cleanup c)))
507 (close (connection.socket-io c))
508 (when (connection.dedicated-output c)
509 (close (connection.dedicated-output c)))
510 (setf *connections* (remove c *connections*))
511 (run-hook *connection-closed-hook* c)
512 (when condition
513 (format *debug-io* "~&;; Connection to Emacs lost.~%;; [~A]~%" condition)
514 (finish-output *debug-io*)))
515
516 (defmacro with-reader-error-handler ((connection) &body body)
517 `(handler-case (progn ,@body)
518 (slime-protocol-error (e)
519 (close-connection ,connection e))))
520
521 (defslimefun simple-break ()
522 (with-simple-restart (continue "Continue from interrupt.")
523 (let ((*debugger-hook* #'swank-debugger-hook))
524 (invoke-debugger
525 (make-condition 'simple-error
526 :format-control "Interrupt from Emacs"))))
527 nil)
528
529 ;;;;;; Thread based communication
530
531 (defvar *active-threads* '())
532
533 (defun read-loop (control-thread input-stream connection)
534 (with-reader-error-handler (connection)
535 (loop (send control-thread (decode-message input-stream)))))
536
537 (defun dispatch-loop (socket-io connection)
538 (let ((*emacs-connection* connection))
539 (handler-case
540 (loop (dispatch-event (receive) socket-io))
541 (error (e)
542 (close-connection connection e)))))
543
544 (defun repl-thread (connection)
545 (let ((thread (connection.repl-thread connection)))
546 (if (thread-alive-p thread)
547 thread
548 (setf (connection.repl-thread connection)
549 (spawn-repl-thread connection "new-repl-thread")))))
550
551
552 (defun find-worker-thread (id)
553 (etypecase id
554 ((member t)
555 (car *active-threads*))
556 ((member :repl-thread)
557 (repl-thread *emacs-connection*))
558 (fixnum
559 (find-thread id))))
560
561 (defun interrupt-worker-thread (id)
562 (let ((thread (or (find-worker-thread id)
563 (repl-thread *emacs-connection*))))
564 (interrupt-thread thread #'simple-break)))
565
566 (defun thread-for-evaluation (id)
567 "Find or create a thread to evaluate the next request."
568 (let ((c *emacs-connection*))
569 (etypecase id
570 ((member t)
571 (spawn-worker-thread c))
572 ((member :repl-thread)
573 (repl-thread c))
574 (fixnum
575 (find-thread id)))))
576
577 (defun spawn-worker-thread (connection)
578 (spawn (lambda ()
579 (with-bindings *default-worker-thread-bindings*
580 (handle-request connection)))
581 :name "worker"))
582
583 (defun spawn-repl-thread (connection name)
584 (spawn (lambda ()
585 (with-bindings *default-worker-thread-bindings*
586 (repl-loop connection)))
587 :name name))
588
589 (defun dispatch-event (event socket-io)
590 "Handle an event triggered either by Emacs or within Lisp."
591 (log-event "DISPATCHING: ~S~%" event)
592 (destructure-case event
593 ((:emacs-rex form package thread-id id)
594 (let ((thread (thread-for-evaluation thread-id)))
595 (push thread *active-threads*)
596 (send thread `(eval-for-emacs ,form ,package ,id))))
597 ((:return thread &rest args)
598 (let ((tail (member thread *active-threads*)))
599 (setq *active-threads* (nconc (ldiff *active-threads* tail)
600 (cdr tail))))
601 (encode-message `(:return ,@args) socket-io))
602 ((:emacs-interrupt thread-id)
603 (interrupt-worker-thread thread-id))
604 (((:debug :debug-condition :debug-activate :debug-return)
605 thread &rest args)
606 (encode-message `(,(car event) ,(thread-id thread) ,@args) socket-io))
607 ((:read-string thread &rest args)
608 (encode-message `(:read-string ,(thread-id thread) ,@args) socket-io))
609 ((:y-or-n-p thread &rest args)
610 (encode-message `(:y-or-n-p ,(thread-id thread) ,@args) socket-io))
611 ((:read-aborted thread &rest args)
612 (encode-message `(:read-aborted ,(thread-id thread) ,@args) socket-io))
613 ((:emacs-return-string thread-id tag string)
614 (send (find-thread thread-id) `(take-input ,tag ,string)))
615 ((:eval thread &rest args)
616 (encode-message `(:eval ,(thread-id thread) ,@args) socket-io))
617 ((:emacs-return thread-id tag value)
618 (send (find-thread thread-id) `(take-input ,tag ,value)))
619 (((:write-string :presentation-start :presentation-end
620 :new-package :new-features :ed :%apply :indentation-update
621 :eval-no-wait :background-message)
622 &rest _)
623 (declare (ignore _))
624 (encode-message event socket-io))))
625
626 (defun spawn-threads-for-connection (connection)
627 (let* ((socket-io (connection.socket-io connection))
628 (control-thread (spawn (lambda ()
629 (let ((*debugger-hook* nil))
630 (dispatch-loop socket-io connection)))
631 :name "control-thread")))
632 (setf (connection.control-thread connection) control-thread)
633 (let ((reader-thread (spawn (lambda ()
634 (let ((*debugger-hook* nil))
635 (read-loop control-thread socket-io
636 connection)))
637 :name "reader-thread"))
638 (repl-thread (spawn-repl-thread connection "repl-thread")))
639 (setf (connection.reader-thread connection) reader-thread)
640 (setf (connection.repl-thread connection) repl-thread)
641 connection)))
642
643 (defun cleanup-connection-threads (connection)
644 (let ((threads (list (connection.repl-thread connection)
645 (connection.reader-thread connection)
646 (connection.control-thread connection))))
647 (dolist (thread threads)
648 (unless (equal (current-thread) thread)
649 (kill-thread thread)))))
650
651 (defun repl-loop (connection)
652 (with-connection (connection)
653 (loop (handle-request connection))))
654
655 (defun process-available-input (stream fn)
656 (loop while (and (open-stream-p stream)
657 (listen stream))
658 do (funcall fn)))
659
660 ;;;;;; Signal driven IO
661
662 (defun install-sigio-handler (connection)
663 (let ((client (connection.socket-io connection)))
664 (flet ((handler ()
665 (cond ((null *swank-state-stack*)
666 (with-reader-error-handler (connection)
667 (process-available-input
668 client (lambda () (handle-request connection)))))
669 ((eq (car *swank-state-stack*) :read-next-form))
670 (t (process-available-input client #'read-from-emacs)))))
671 (add-sigio-handler client #'handler)
672 (handler))))
673
674 (defun deinstall-sigio-handler (connection)
675 (remove-sigio-handlers (connection.socket-io connection)))
676
677 ;;;;;; SERVE-EVENT based IO
678
679 (defun install-fd-handler (connection)
680 (let ((client (connection.socket-io connection)))
681 (flet ((handler ()
682 (cond ((null *swank-state-stack*)
683 (with-reader-error-handler (connection)
684 (process-available-input
685 client (lambda () (handle-request connection)))))
686 ((eq (car *swank-state-stack*) :read-next-form))
687 (t (process-available-input client #'read-from-emacs)))))
688 (setq *debugger-hook*
689 (lambda (c h)
690 (with-reader-error-handler (connection)
691 (block debugger
692 (with-connection (connection)
693 (swank-debugger-hook c h)
694 (return-from debugger))
695 (abort)))))
696 (add-fd-handler client #'handler)
697 (handler))))
698
699 (defun deinstall-fd-handler (connection)
700 (remove-fd-handlers (connection.socket-io connection)))
701
702 ;;;;;; Simple sequential IO
703
704 (defun simple-serve-requests (connection)
705 (with-reader-error-handler (connection)
706 (unwind-protect (loop (with-simple-restart
707 (abort "Return to SLIME top-level.")
708 (handle-request connection)))
709 (close-connection connection))))
710
711 (defun read-from-socket-io ()
712 (let ((event (decode-message (current-socket-io))))
713 (log-event "DISPATCHING: ~S~%" event)
714 (destructure-case event
715 ((:emacs-rex form package thread id)
716 (declare (ignore thread))
717 `(eval-for-emacs ,form ,package ,id))
718 ((:emacs-interrupt thread)
719 (declare (ignore thread))
720 '(simple-break))
721 ((:emacs-return-string thread tag string)
722 (declare (ignore thread))
723 `(take-input ,tag ,string))
724 ((:emacs-return thread tag value)
725 (declare (ignore thread))
726 `(take-input ,tag ,value)))))
727
728 (defun send-to-socket-io (event)
729 (log-event "DISPATCHING: ~S~%" event)
730 (flet ((send (o)
731 (without-interrupts
732 (encode-message o (current-socket-io)))))
733 (destructure-case event
734 (((:debug-activate :debug :debug-return :read-string :read-aborted
735 :y-or-n-p :eval)
736 thread &rest args)
737 (declare (ignore thread))
738 (send `(,(car event) 0 ,@args)))
739 ((:return thread &rest args)
740 (declare (ignore thread))
741 (send `(:return ,@args)))
742 (((:write-string :new-package :new-features :debug-condition
743 :presentation-start :presentation-end
744 :indentation-update :ed :%apply :eval-no-wait
745 :background-message)
746 &rest _)
747 (declare (ignore _))
748 (send event)))))
749
750 (defun initialize-streams-for-connection (connection)
751 (multiple-value-bind (dedicated in out io) (open-streams connection)
752 (setf (connection.dedicated-output connection) dedicated
753 (connection.user-io connection) io
754 (connection.user-output connection) out
755 (connection.user-input connection) in)
756 connection))
757
758 (defun create-connection (socket-io style external-format)
759 (let ((c (ecase style
760 (:spawn
761 (make-connection :socket-io socket-io
762 :read #'read-from-control-thread
763 :send #'send-to-control-thread
764 :serve-requests #'spawn-threads-for-connection
765 :cleanup #'cleanup-connection-threads))
766 (:sigio
767 (make-connection :socket-io socket-io
768 :read #'read-from-socket-io
769 :send #'send-to-socket-io
770 :serve-requests #'install-sigio-handler
771 :cleanup #'deinstall-sigio-handler))
772 (:fd-handler
773 (make-connection :socket-io socket-io
774 :read #'read-from-socket-io
775 :send #'send-to-socket-io
776 :serve-requests #'install-fd-handler
777 :cleanup #'deinstall-fd-handler))
778 ((nil)
779 (make-connection :socket-io socket-io
780 :read #'read-from-socket-io
781 :send #'send-to-socket-io
782 :serve-requests #'simple-serve-requests)))))
783 (setf (connection.communication-style c) style)
784 (setf (connection.external-format c) external-format)
785 (initialize-streams-for-connection c)
786 c))
787
788
789 ;;;; IO to Emacs
790 ;;;
791 ;;; This code handles redirection of the standard I/O streams
792 ;;; (`*standard-output*', etc) into Emacs. The `connection' structure
793 ;;; contains the appropriate streams, so all we have to do is make the
794 ;;; right bindings.
795
796 ;;;;; Global I/O redirection framework
797 ;;;
798 ;;; Optionally, the top-level global bindings of the standard streams
799 ;;; can be assigned to be redirected to Emacs. When Emacs connects we
800 ;;; redirect the streams into the connection, and they keep going into
801 ;;; that connection even if more are established. If the connection
802 ;;; handling the streams closes then another is chosen, or if there
803 ;;; are no connections then we revert to the original (real) streams.
804 ;;;
805 ;;; It is slightly tricky to assign the global values of standard
806 ;;; streams because they are often shadowed by dynamic bindings. We
807 ;;; solve this problem by introducing an extra indirection via synonym
808 ;;; streams, so that *STANDARD-INPUT* is a synonym stream to
809 ;;; *CURRENT-STANDARD-INPUT*, etc. We never shadow the "current"
810 ;;; variables, so they can always be assigned to affect a global
811 ;;; change.
812
813 (defvar *globally-redirect-io* nil
814 "When non-nil globally redirect all standard streams to Emacs.")
815
816 (defmacro setup-stream-indirection (stream-var)
817 "Setup redirection scaffolding for a global stream variable.
818 Supposing (for example) STREAM-VAR is *STANDARD-INPUT*, this macro:
819
820 1. Saves the value of *STANDARD-INPUT* in a variable called
821 *REAL-STANDARD-INPUT*.
822
823 2. Creates *CURRENT-STANDARD-INPUT*, initially with the same value as
824 *STANDARD-INPUT*.
825
826 3. Assigns *STANDARD-INPUT* to a synonym stream pointing to
827 *CURRENT-STANDARD-INPUT*.
828
829 This has the effect of making *CURRENT-STANDARD-INPUT* contain the
830 effective global value for *STANDARD-INPUT*. This way we can assign
831 the effective global value even when *STANDARD-INPUT* is shadowed by a
832 dynamic binding."
833 (let ((real-stream-var (prefixed-var "REAL" stream-var))
834 (current-stream-var (prefixed-var "CURRENT" stream-var)))
835 `(progn
836 ;; Save the real stream value for the future.
837 (defvar ,real-stream-var ,stream-var)
838 ;; Define a new variable for the effective stream.
839 ;; This can be reassigned.
840 (defvar ,current-stream-var ,stream-var)
841 ;; Assign the real binding as a synonym for the current one.
842 (setq ,stream-var (make-synonym-stream ',current-stream-var)))))
843
844 (eval-when (:compile-toplevel :load-toplevel :execute)
845 (defun prefixed-var (prefix variable-symbol)
846 "(PREFIXED-VAR \"FOO\" '*BAR*) => SWANK::*FOO-BAR*"
847 (let ((basename (subseq (symbol-name variable-symbol) 1)))
848 (intern (format nil "*~A-~A" prefix basename) :swank))))
849
850 ;;;;; Global redirection setup
851
852 (setup-stream-indirection *standard-output*)
853 (setup-stream-indirection *error-output*)
854 (setup-stream-indirection *trace-output*)
855 (setup-stream-indirection *standard-input*)
856 (setup-stream-indirection *debug-io*)
857 (setup-stream-indirection *query-io*)
858 (setup-stream-indirection *terminal-io*)
859
860 (defparameter *standard-output-streams*
861 '(*standard-output* *error-output* *trace-output*)
862 "The symbols naming standard output streams.")
863
864 (defparameter *standard-input-streams*
865 '(*standard-input*)
866 "The symbols naming standard input streams.")
867
868 (defparameter *standard-io-streams*
869 '(*debug-io* *query-io* *terminal-io*)
870 "The symbols naming standard io streams.")
871
872 (defun globally-redirect-io-to-connection (connection)
873 "Set the standard I/O streams to redirect to CONNECTION.
874 Assigns *CURRENT-<STREAM>* for all standard streams."
875 (dolist (o *standard-output-streams*)
876 (set (prefixed-var "CURRENT" o)
877 (connection.user-output connection)))
878 ;; FIXME: If we redirect standard input to Emacs then we get the
879 ;; regular Lisp top-level trying to read from our REPL.
880 ;;
881 ;; Perhaps the ideal would be for the real top-level to run in a
882 ;; thread with local bindings for all the standard streams. Failing
883 ;; that we probably would like to inhibit it from reading while
884 ;; Emacs is connected.
885 ;;
886 ;; Meanwhile we just leave *standard-input* alone.
887 #+NIL
888 (dolist (i *standard-input-streams*)
889 (set (prefixed-var "CURRENT" i)
890 (connection.user-input connection)))
891 (dolist (io *standard-io-streams*)
892 (set (prefixed-var "CURRENT" io)
893 (connection.user-io connection))))
894
895 (defun revert-global-io-redirection ()
896 "Set *CURRENT-<STREAM>* to *REAL-<STREAM>* for all standard streams."
897 (dolist (stream-var (append *standard-output-streams*
898 *standard-input-streams*
899 *standard-io-streams*))
900 (set (prefixed-var "CURRENT" stream-var)
901 (symbol-value (prefixed-var "REAL" stream-var)))))
902
903 ;;;;; Global redirection hooks
904
905 (defvar *global-stdio-connection* nil
906 "The connection to which standard I/O streams are globally redirected.
907 NIL if streams are not globally redirected.")
908
909 (defun maybe-redirect-global-io (connection)
910 "Consider globally redirecting to a newly-established CONNECTION."
911 (when (and *globally-redirect-io* (null *global-stdio-connection*))
912 (setq *global-stdio-connection* connection)
913 (globally-redirect-io-to-connection connection)))
914
915 (defun update-redirection-after-close (closed-connection)
916 "Update redirection after a connection closes."
917 (when (eq *global-stdio-connection* closed-connection)
918 (if (and (default-connection) *globally-redirect-io*)
919 ;; Redirect to another connection.
920 (globally-redirect-io-to-connection (default-connection))
921 ;; No more connections, revert to the real streams.
922 (progn (revert-global-io-redirection)
923 (setq *global-stdio-connection* nil)))))
924
925 (add-hook *new-connection-hook* 'maybe-redirect-global-io)
926 (add-hook *connection-closed-hook* 'update-redirection-after-close)
927
928 ;;;;; Redirection during requests
929 ;;;
930 ;;; We always redirect the standard streams to Emacs while evaluating
931 ;;; an RPC. This is done with simple dynamic bindings.
932
933 (defun call-with-redirected-io (connection function)
934 "Call FUNCTION with I/O streams redirected via CONNECTION."
935 (declare (type function function))
936 (let* ((io (connection.user-io connection))
937 (in (connection.user-input connection))
938 (out (connection.user-output connection))
939 (*standard-output* out)
940 (*error-output* out)
941 (*trace-output* out)
942 (*debug-io* io)
943 (*query-io* io)
944 (*standard-input* in)
945 (*terminal-io* io))
946 (funcall function)))
947
948 (defun read-from-emacs ()
949 "Read and process a request from Emacs."
950 (apply #'funcall (funcall (connection.read *emacs-connection*))))
951
952 (defun read-from-control-thread ()
953 (receive))
954
955 (defun decode-message (stream)
956 "Read an S-expression from STREAM using the SLIME protocol.
957 If a protocol error occurs then a SLIME-PROTOCOL-ERROR is signalled."
958 (let ((*swank-state-stack* (cons :read-next-form *swank-state-stack*)))
959 (handler-case
960 (let* ((length (decode-message-length stream))
961 (string (make-string length))
962 (pos (read-sequence string stream)))
963 (assert (= pos length) ()
964 "Short read: length=~D pos=~D" length pos)
965 (let ((form (read-form string)))
966 (log-event "READ: ~A~%" string)
967 form))
968 (serious-condition (c)
969 (error (make-condition 'slime-protocol-error :condition c))))))
970
971 (defun decode-message-length (stream)
972 (let ((buffer (make-string 6)))
973 (dotimes (i 6)
974 (setf (aref buffer i) (read-char stream)))
975 (parse-integer buffer :radix #x10)))
976
977 (defun read-form (string)
978 (with-standard-io-syntax
979 (let ((*package* *swank-io-package*))
980 (read-from-string string))))
981
982 (defvar *slime-features* nil
983 "The feature list that has been sent to Emacs.")
984
985 (defun send-to-emacs (object)
986 "Send OBJECT to Emacs."
987 (funcall (connection.send *emacs-connection*) object))
988
989 (defun send-oob-to-emacs (object)
990 (send-to-emacs object))
991
992 (defun send-to-control-thread (object)
993 (send (connection.control-thread *emacs-connection*) object))
994
995 (defun encode-message (message stream)
996 (let* ((string (prin1-to-string-for-emacs message))
997 (length (length string)))
998 (log-event "WRITE: ~A~%" string)
999 (let ((*print-pretty* nil))
1000 (format stream "~6,'0x" length))
1001 (write-string string stream)
1002 ;;(terpri stream)
1003 (force-output stream)))
1004
1005 (defun prin1-to-string-for-emacs (object)
1006 (with-standard-io-syntax
1007 (let ((*print-case* :downcase)
1008 (*print-readably* nil)
1009 (*print-pretty* nil)
1010 (*package* *swank-io-package*))
1011 (prin1-to-string object))))
1012
1013 (defun force-user-output ()
1014 (force-output (connection.user-io *emacs-connection*))
1015 (finish-output (connection.user-output *emacs-connection*)))
1016
1017 (defun clear-user-input ()
1018 (clear-input (connection.user-input *emacs-connection*)))
1019
1020 (defvar *read-input-catch-tag* 0)
1021
1022 (defun intern-catch-tag (tag)
1023 ;; fixnums aren't eq in ABCL, so we use intern to create tags
1024 (intern (format nil "~D" tag) :swank))
1025
1026 (defun read-user-input-from-emacs ()
1027 (let ((tag (incf *read-input-catch-tag*)))
1028 (force-output)
1029 (send-to-emacs `(:read-string ,(current-thread) ,tag))
1030 (let ((ok nil))
1031 (unwind-protect
1032 (prog1 (catch (intern-catch-tag tag)
1033 (loop (read-from-emacs)))
1034 (setq ok t))
1035 (unless ok
1036 (send-to-emacs `(:read-aborted ,(current-thread) ,tag)))))))
1037
1038 (defun y-or-n-p-in-emacs (format-string &rest arguments)
1039 "Like y-or-n-p, but ask in the Emacs minibuffer."
1040 (let ((tag (incf *read-input-catch-tag*))
1041 (question (apply #'format nil format-string arguments)))
1042 (force-output)
1043 (send-to-emacs `(:y-or-n-p ,(current-thread) ,tag ,question))
1044 (catch (intern-catch-tag tag)
1045 (loop (read-from-emacs)))))
1046
1047 (defslimefun take-input (tag input)
1048 "Return the string INPUT to the continuation TAG."
1049 (throw (intern-catch-tag tag) input))
1050
1051 (defun process-form-for-emacs (form)
1052 "Returns a string which emacs will read as equivalent to
1053 FORM. FORM can contain lists, strings, characters, symbols and
1054 numbers.
1055
1056 Characters are converted emacs' ?<char> notaion, strings are left
1057 as they are (except for espacing any nested \" chars, numbers are
1058 printed in base 10 and symbols are printed as their symbol-nome
1059 converted to lower case."
1060 (etypecase form
1061 (string (format nil "~S" form))
1062 (cons (format nil "(~A . ~A)"
1063 (process-form-for-emacs (car form))
1064 (process-form-for-emacs (cdr form))))
1065 (character (format nil "?~C" form))
1066 (symbol (string-downcase (symbol-name form)))
1067 (number (let ((*print-base* 10))
1068 (princ-to-string form)))))
1069
1070 (defun eval-in-emacs (form &optional nowait)
1071 "Eval FORM in Emacs."
1072 (cond (nowait
1073 (send-to-emacs `(:eval-no-wait ,(process-form-for-emacs form))))
1074 (t
1075 (force-output)
1076 (let* ((tag (incf *read-input-catch-tag*))
1077 (value (catch (intern-catch-tag tag)
1078 (send-to-emacs
1079 `(:eval ,(current-thread) ,tag
1080 ,(process-form-for-emacs form)))
1081 (loop (read-from-emacs)))))
1082 (destructure-case value
1083 ((:ok value) value)
1084 ((:abort) (abort)))))))
1085
1086 (defslimefun connection-info ()
1087 "Return a key-value list of the form:
1088 \(&key PID STYLE LISP-IMPLEMENTATION MACHINE FEATURES PACKAGE)
1089 PID: is the process-id of Lisp process (or nil, depending on the STYLE)
1090 STYLE: the communication style
1091 LISP-IMPLEMENTATION: a list (&key TYPE NAME VERSION)
1092 FEATURES: a list of keywords
1093 PACKAGE: a list (&key NAME PROMPT)"
1094 (setq *slime-features* *features*)
1095 `(:pid ,(getpid) :style ,(connection.communication-style *emacs-connection*)
1096 :lisp-implementation (:type ,(lisp-implementation-type)
1097 :name ,(lisp-implementation-type-name)
1098 :version ,(lisp-implementation-version))
1099 :machine (:instance ,(machine-instance)
1100 :type ,(machine-type)
1101 :version ,(machine-version))
1102 :features ,(features-for-emacs)
1103 :package (:name ,(package-name *package*)
1104 :prompt ,(package-string-for-prompt *package*))))
1105
1106 (defslimefun io-speed-test (&optional (n 5000) (m 1))
1107 (let* ((s *standard-output*)
1108 (*trace-output* (make-broadcast-stream s *log-output*)))
1109 (time (progn
1110 (dotimes (i n)
1111 (format s "~D abcdefghijklm~%" i)
1112 (when (zerop (mod n m))
1113 (force-output s)))
1114 (finish-output s)
1115 (when *emacs-connection*
1116 (eval-in-emacs '(message "done.")))))
1117 (terpri *trace-output*)
1118 (finish-output *trace-output*)
1119 nil))
1120
1121
1122 ;;;; Reading and printing
1123
1124 (defmacro define-special (name doc)
1125 "Define a special variable NAME with doc string DOC.
1126 This is like defvar, but NAME will not be initialized."
1127 `(progn
1128 (defvar ,name)
1129 (setf (documentation ',name 'variable) ,doc)))
1130
1131 (define-special *buffer-package*
1132 "Package corresponding to slime-buffer-package.
1133
1134 EVAL-FOR-EMACS binds *buffer-package*. Strings originating from a slime
1135 buffer are best read in this package. See also FROM-STRING and TO-STRING.")
1136
1137 (define-special *buffer-readtable*
1138 "Readtable associated with the current buffer")
1139
1140 (defmacro with-buffer-syntax ((&rest _) &body body)
1141 "Execute BODY with appropriate *package* and *readtable* bindings.
1142
1143 This should be used for code that is conceptionally executed in an
1144 Emacs buffer."
1145 (destructuring-bind () _
1146 `(call-with-buffer-syntax (lambda () ,@body))))
1147
1148 (defun call-with-buffer-syntax (fun)
1149 (let ((*package* *buffer-package*))
1150 ;; Don't shadow *readtable* unnecessarily because that prevents
1151 ;; the user from assigning to it.
1152 (if (eq *readtable* *buffer-readtable*)
1153 (call-with-syntax-hooks fun)
1154 (let ((*readtable* *buffer-readtable*))
1155 (call-with-syntax-hooks fun)))))
1156
1157 (defun to-string (object)
1158 "Write OBJECT in the *BUFFER-PACKAGE*.
1159 The result may not be readable. Handles problems with PRINT-OBJECT methods
1160 gracefully."
1161 (with-buffer-syntax ()
1162 (let ((*print-readably* nil))
1163 (handler-case
1164 (prin1-to-string object)
1165 (error ()
1166 (with-output-to-string (s)
1167 (print-unreadable-object (object s :type t :identity t)
1168 (princ "<<error printing object>>" s))))))))
1169
1170 (defun from-string (string)
1171 "Read string in the *BUFFER-PACKAGE*"
1172 (with-buffer-syntax ()
1173 (let ((*read-suppress* nil))
1174 (read-from-string string))))
1175
1176 ;; FIXME: deal with #\| etc. hard to do portably.
1177 (defun tokenize-symbol (string)
1178 (let ((package (let ((pos (position #\: string)))
1179 (if pos (subseq string 0 pos) nil)))
1180 (symbol (let ((pos (position #\: string :from-end t)))
1181 (if pos (subseq string (1+ pos)) string)))
1182 (internp (search "::" string)))
1183 (values symbol package internp)))
1184
1185 ;; FIXME: Escape chars are ignored
1186 (defun casify (string)
1187 "Convert string accoring to readtable-case."
1188 (ecase (readtable-case *readtable*)
1189 (:preserve string)
1190 (:upcase (string-upcase string))
1191 (:downcase (string-downcase string))
1192 (:invert (multiple-value-bind (lower upper) (determine-case string)
1193 (cond ((and lower upper) string)
1194 (lower (string-upcase string))
1195 (upper (string-downcase string))
1196 (t string))))))
1197
1198 (defun parse-symbol (string &optional (package *package*))
1199 "Find the symbol named STRING.
1200 Return the symbol and a flag indicating whether the symbols was found."
1201 (multiple-value-bind (sname pname) (tokenize-symbol string)
1202 (let ((package (cond ((string= pname "") keyword-package)
1203 (pname (find-package (casify pname)))
1204 (t package))))
1205 (if package
1206 (find-symbol (casify sname) package)
1207 (values nil nil)))))
1208
1209 (defun parse-symbol-or-lose (string &optional (package *package*))
1210 (multiple-value-bind (symbol status) (parse-symbol string package)
1211 (if status
1212 (values symbol status)
1213 (error "Unknown symbol: ~A [in ~A]" string package))))
1214
1215 ;; FIXME: interns the name
1216 (defun parse-package (string)
1217 "Find the package named STRING.
1218 Return the package or nil."
1219 (multiple-value-bind (name pos)
1220 (if (zerop (length string))
1221 (values :|| 0)
1222 (let ((*package* keyword-package))
1223 (ignore-errors (read-from-string string))))
1224 (if (and (or (keywordp name) (stringp name))
1225 (= (length string) pos))
1226 (find-package name))))
1227
1228 (defun guess-package-from-string (name &optional (default-package *package*))
1229 (or (and name
1230 (or (parse-package name)
1231 (find-package (string-upcase name))
1232 (parse-package (substitute #\- #\! name))))
1233 default-package))
1234
1235 (defvar *readtable-alist* (default-readtable-alist)
1236 "An alist mapping package names to readtables.")
1237
1238 (defun guess-buffer-readtable (package-name &optional (default *readtable*))
1239 (let ((package (guess-package-from-string package-name)))
1240 (if package
1241 (or (cdr (assoc (package-name package) *readtable-alist*
1242 :test #'string=))
1243 default)
1244 default)))
1245
1246 (defun valid-operator-symbol-p (symbol)
1247 "Test if SYMBOL names a function, macro, or special-operator."
1248 (or (fboundp symbol)
1249 (macro-function symbol)
1250 (special-operator-p symbol)))
1251
1252 (defun valid-operator-name-p (string)
1253 "Test if STRING names a function, macro, or special-operator."
1254 (let ((symbol (parse-symbol string)))
1255 (valid-operator-symbol-p symbol)))
1256
1257
1258 ;;;; Arglists
1259
1260 (defslimefun arglist-for-echo-area (names)
1261 "Return the arglist for the first function, macro, or special-op in NAMES."
1262 (handler-case
1263 (with-buffer-syntax ()
1264 (let ((name (find-if #'valid-operator-name-p names)))
1265 (if name (format-arglist-for-echo-area (parse-symbol name) name))))
1266 (error (cond)
1267 (format nil "ARGLIST: ~A" cond))))
1268
1269 (defun format-arglist-for-echo-area (symbol name)
1270 "Return SYMBOL's arglist as string for display in the echo area.
1271 Use the string NAME as operator name."
1272 (let ((arglist (arglist symbol)))
1273 (etypecase arglist
1274 ((member :not-available)
1275 nil)
1276 (list
1277 (let ((enriched-arglist
1278 (if (extra-keywords symbol)
1279 ;; When there are extra keywords, we decode the
1280 ;; arglist, merge in the keywords and encode it
1281 ;; again.
1282 (let ((decoded-arglist (decode-arglist arglist)))
1283 (enrich-decoded-arglist-with-extra-keywords
1284 decoded-arglist (list symbol))
1285 (encode-arglist decoded-arglist))
1286 ;; Otherwise, just use the original arglist.
1287 ;; This works better for implementation-specific
1288 ;; lambda-list-keywords like CMUCL's &parse-body.
1289 arglist)))
1290 (arglist-to-string (cons name enriched-arglist)
1291 (symbol-package symbol)))))))
1292
1293 (defun clean-arglist (arglist)
1294 "Remove &whole, &enviroment, and &aux elements from ARGLIST."
1295 (cond ((null arglist) '())
1296 ((member (car arglist) '(&whole &environment))
1297 (clean-arglist (cddr arglist)))
1298 ((eq (car arglist) '&aux)
1299 '())
1300 (t (cons (car arglist) (clean-arglist (cdr arglist))))))
1301
1302 (defun arglist-to-string (arglist package)
1303 "Print the list ARGLIST for display in the echo area.
1304 The argument name are printed without package qualifiers and
1305 pretty printing of (function foo) as #'foo is suppressed."
1306 (setq arglist (clean-arglist arglist))
1307 (etypecase arglist
1308 (null "()")
1309 (cons
1310 (with-output-to-string (*standard-output*)
1311 (with-standard-io-syntax
1312 (let ((*package* package) (*print-case* :downcase)
1313 (*print-pretty* t) (*print-circle* nil) (*print-readably* nil)
1314 (*print-level* 10) (*print-length* 20))
1315 (pprint-logical-block (nil nil :prefix "(" :suffix ")")
1316 (loop
1317 (let ((arg (pop arglist)))
1318 (etypecase arg
1319 (symbol (princ arg))
1320 (string (princ arg))
1321 (cons (pprint-logical-block (nil nil :prefix "(" :suffix ")")
1322 (princ (car arg))
1323 (unless (null (cdr arg))
1324 (write-char #\space))
1325 (pprint-fill *standard-output* (cdr arg) nil))))
1326 (when (null arglist) (return))
1327 (write-char #\space)
1328 (pprint-newline :fill))))))))))
1329
1330 (defun test-print-arglist (list string)
1331 (string= (arglist-to-string list (find-package :swank)) string))
1332
1333 ;; Should work:
1334 (progn
1335 (assert (test-print-arglist '(function cons) "(function cons)"))
1336 (assert (test-print-arglist '(quote cons) "(quote cons)"))
1337 (assert (test-print-arglist '(&key (function #'+)) "(&key (function #'+))"))
1338 (assert (test-print-arglist '(&whole x y z) "(y z)"))
1339 (assert (test-print-arglist '(x &aux y z) "(x)"))
1340 (assert (test-print-arglist '(x &environment env y) "(x y)")))
1341 ;; Expected failure:
1342 ;; (assert (test-print-arglist '(&key ((function f))) "(&key ((function f)))"))
1343
1344 (defslimefun variable-desc-for-echo-area (variable-name)
1345 "Return a short description of VARIABLE-NAME, or NIL."
1346 (with-buffer-syntax ()
1347 (let ((sym (parse-symbol variable-name)))
1348 (if (and sym (boundp sym))
1349 (let ((*print-pretty* nil) (*print-level* 4)
1350 (*print-length* 10) (*print-circle* t))
1351 (format nil "~A => ~A" sym (symbol-value sym)))))))
1352
1353 (defstruct (keyword-arg
1354 (:conc-name keyword-arg.)
1355 (:constructor make-keyword-arg (keyword arg-name default-arg)))
1356 keyword
1357 arg-name
1358 default-arg)
1359
1360 (defun decode-keyword-arg (arg)
1361 "Decode a keyword item of formal argument list.
1362 Return three values: keyword, argument name, default arg."
1363 (cond ((symbolp arg)
1364 (make-keyword-arg (intern (symbol-name arg) keyword-package)
1365 arg
1366 nil))
1367 ((and (consp arg)
1368 (consp (car arg)))
1369 (make-keyword-arg (caar arg)
1370 (cadar arg)
1371 (cadr arg)))
1372 ((consp arg)
1373 (make-keyword-arg (intern (symbol-name (car arg)) keyword-package)
1374 (car arg)
1375 (cadr arg)))
1376 (t
1377 (error "Bad keyword item of formal argument list"))))
1378
1379 (defun encode-keyword-arg (arg)
1380 (if (eql (intern (symbol-name (keyword-arg.arg-name arg))
1381 keyword-package)
1382 (keyword-arg.keyword arg))
1383 (if (keyword-arg.default-arg arg)
1384 (list (keyword-arg.arg-name arg)
1385 (keyword-arg.default-arg arg))
1386 (keyword-arg.arg-name arg))
1387 (let ((keyword/name (list (keyword-arg.arg-name arg)
1388 (keyword-arg.keyword arg))))
1389 (if (keyword-arg.default-arg arg)
1390 (list keyword/name
1391 (keyword-arg.default-arg arg))
1392 (list keyword/name)))))
1393
1394 (progn
1395 (assert (equalp (decode-keyword-arg 'x)
1396 (make-keyword-arg :x 'x nil)))
1397 (assert (equalp (decode-keyword-arg '(x t))
1398 (make-keyword-arg :x 'x t)))
1399 (assert (equalp (decode-keyword-arg '((:x y)))
1400 (make-keyword-arg :x 'y nil)))
1401 (assert (equalp (decode-keyword-arg '((:x y) t))
1402 (make-keyword-arg :x 'y t))))
1403
1404 (defstruct (optional-arg
1405 (:conc-name optional-arg.)
1406 (:constructor make-optional-arg (arg-name default-arg)))
1407 arg-name
1408 default-arg)
1409
1410 (defun decode-optional-arg (arg)
1411 "Decode an optional item of a formal argument list.
1412 Return an OPTIONAL-ARG structure."
1413 (etypecase arg
1414 (symbol (make-optional-arg arg nil))
1415 (list (make-optional-arg (car arg) (cadr arg)))))
1416
1417 (defun encode-optional-arg (optional-arg)
1418 (if (optional-arg.default-arg optional-arg)
1419 (list (optional-arg.arg-name optional-arg)
1420 (optional-arg.default-arg optional-arg))
1421 (optional-arg.arg-name optional-arg)))
1422
1423 (progn
1424 (assert (equalp (decode-optional-arg 'x)
1425 (make-optional-arg 'x nil)))
1426 (assert (equalp (decode-optional-arg '(x t))
1427 (make-optional-arg 'x t))))
1428
1429 (defstruct (arglist (:conc-name arglist.))
1430 required-args ; list of the required arguments
1431 optional-args ; list of the optional arguments
1432 key-p ; whether &key appeared
1433 keyword-args ; list of the keywords
1434 rest ; name of the &rest or &body argument (if any)
1435 body-p ; whether the rest argument is a &body
1436 allow-other-keys-p) ; whether &allow-other-keys appeared
1437
1438 (defun decode-arglist (arglist)
1439 "Parse the list ARGLIST and return an ARGLIST structure."
1440 (let ((mode nil)
1441 (result (make-arglist)))
1442 (dolist (arg arglist)
1443 (cond
1444 ((eql arg '&allow-other-keys)
1445 (setf (arglist.allow-other-keys-p result) t))
1446 ((eql arg '&key)
1447 (setf (arglist.key-p result) t
1448 mode arg))
1449 ((member arg lambda-list-keywords)
1450 (setq mode arg))
1451 (t
1452 (case mode
1453 (&key
1454 (push (decode-keyword-arg arg)
1455 (arglist.keyword-args result)))
1456 (&optional
1457 (push (decode-optional-arg arg)
1458 (arglist.optional-args result)))
1459 (&body
1460 (setf (arglist.body-p result) t
1461 (arglist.rest result) arg))
1462 (&rest
1463 (setf (arglist.rest result) arg))
1464 ((nil)
1465 (push arg (arglist.required-args result)))
1466 ((&whole &environment)
1467 (setf mode nil))))))
1468 (setf (arglist.required-args result)
1469 (nreverse (arglist.required-args result)))
1470 (setf (arglist.optional-args result)
1471 (nreverse (arglist.optional-args result)))
1472 (setf (arglist.keyword-args result)
1473 (nreverse (arglist.keyword-args result)))
1474 result))
1475
1476 (defun encode-arglist (decoded-arglist)
1477 (append (arglist.required-args decoded-arglist)
1478 (when (arglist.optional-args decoded-arglist)
1479 '(&optional))
1480 (mapcar #'encode-optional-arg (arglist.optional-args decoded-arglist))
1481 (when (arglist.key-p decoded-arglist)
1482 '(&key))
1483 (mapcar #'encode-keyword-arg (arglist.keyword-args decoded-arglist))
1484 (when (arglist.allow-other-keys-p decoded-arglist)
1485 '(&allow-other-keys))
1486 (cond ((not (arglist.rest decoded-arglist))
1487 '())
1488 ((arglist.body-p decoded-arglist)
1489 `(&body ,(arglist.rest decoded-arglist)))
1490 (t
1491 `(&rest ,(arglist.rest decoded-arglist))))))
1492
1493 (defun arglist-keywords (arglist)
1494 "Return the list of keywords in ARGLIST.
1495 As a secondary value, return whether &allow-other-keys appears."
1496 (let ((decoded-arglist (decode-arglist arglist)))
1497 (values (arglist.keyword-args decoded-arglist)
1498 (arglist.allow-other-keys-p decoded-arglist))))
1499
1500 (defun methods-keywords (methods)
1501 "Collect all keywords in the arglists of METHODS.
1502 As a secondary value, return whether &allow-other-keys appears somewhere."
1503 (let ((keywords '())
1504 (allow-other-keys nil))
1505 (dolist (method methods)
1506 (multiple-value-bind (kw aok)
1507 (arglist-keywords
1508 (swank-mop:method-lambda-list method))
1509 (setq keywords (remove-duplicates (append keywords kw)
1510 :key #'keyword-arg.keyword)
1511 allow-other-keys (or allow-other-keys aok))))
1512 (values keywords allow-other-keys)))
1513
1514 (defun generic-function-keywords (generic-function)
1515 "Collect all keywords in the methods of GENERIC-FUNCTION.
1516 As a secondary value, return whether &allow-other-keys appears somewhere."
1517 (methods-keywords
1518 (swank-mop:generic-function-methods generic-function)))
1519
1520 (defun applicable-methods-keywords (generic-function classes)
1521 "Collect all keywords in the methods of GENERIC-FUNCTION that are
1522 applicable for argument of CLASSES. As a secondary value, return
1523 whether &allow-other-keys appears somewhere."
1524 (methods-keywords
1525 (swank-mop:compute-applicable-methods-using-classes
1526 generic-function classes)))
1527
1528 (defun arglist-to-template-string (arglist package)
1529 "Print the list ARGLIST for insertion as a template for a function call."
1530 (decoded-arglist-to-template-string
1531 (decode-arglist arglist) package))
1532
1533 (defun decoded-arglist-to-template-string (decoded-arglist package &key (prefix "(") (suffix ")"))
1534 (with-output-to-string (*standard-output*)
1535 (with-standard-io-syntax
1536 (let ((*package* package) (*print-case* :downcase)
1537 (*print-pretty* t) (*print-circle* nil) (*print-readably* nil)
1538 (*print-level* 10) (*print-length* 20))
1539 (pprint-logical-block (nil nil :prefix prefix :suffix suffix)
1540 (print-decoded-arglist-as-template decoded-arglist))))))
1541
1542 (defun print-decoded-arglist-as-template (decoded-arglist)
1543 (let ((first-p t))
1544 (flet ((space ()
1545 (unless first-p
1546 (write-char #\space)
1547 (pprint-newline :fill))
1548 (setq first-p nil)))
1549 (dolist (arg (arglist.required-args decoded-arglist))
1550 (space)
1551 (princ arg))
1552 (dolist (arg (arglist.optional-args decoded-arglist))
1553 (space)
1554 (format t "[~A]" (optional-arg.arg-name arg)))
1555 (dolist (keyword-arg (arglist.keyword-args decoded-arglist))
1556 (space)
1557 (let ((arg-name (keyword-arg.arg-name keyword-arg))
1558 (keyword (keyword-arg.keyword keyword-arg)))
1559 (format t "~W ~A"
1560 (if (keywordp keyword) keyword `',keyword)
1561 arg-name)))
1562 (when (and (arglist.rest decoded-arglist)
1563 (or (not (arglist.keyword-args decoded-arglist))
1564 (arglist.allow-other-keys-p decoded-arglist)))
1565 (if (arglist.body-p decoded-arglist)
1566 (pprint-newline :mandatory)
1567 (space))
1568 (format t "~A..." (arglist.rest decoded-arglist)))))
1569 (pprint-newline :fill))
1570
1571 (defgeneric extra-keywords (operator &rest args)
1572 (:documentation "Return a list of extra keywords of OPERATOR (a
1573 symbol) when applied to the (unevaluated) ARGS. As a secondary value,
1574 return whether other keys are allowed."))
1575
1576 (defmethod extra-keywords (operator &rest args)
1577 ;; default method
1578 (declare (ignore args))
1579 (let ((symbol-function (symbol-function operator)))
1580 (if (typep symbol-function 'generic-function)
1581 (generic-function-keywords symbol-function)
1582 nil)))
1583
1584 (defmethod extra-keywords ((operator (eql 'make-instance))
1585 &rest args)
1586 (unless (null args)
1587 (let ((class-name-form (car args)))
1588 (when (and (listp class-name-form)
1589 (= (length class-name-form) 2)
1590 (eq (car class-name-form) 'quote))
1591 (let* ((class-name (cadr class-name-form))
1592 (class (find-class class-name nil)))
1593 (unless (swank-mop:class-finalized-p class)
1594 ;; Try to finalize the class, which can fail if
1595 ;; superclasses are not defined yet
1596 (handler-case (swank-mop:finalize-inheritance class)
1597 (program-error (c)
1598 (declare (ignore c)))))
1599 (when class
1600 ;; We have the case (make-instance 'CLASS ...)
1601 ;; with a known CLASS.
1602 (multiple-value-bind (slots allow-other-keys-p)
1603 (if (swank-mop:class-finalized-p class)
1604 (values (swank-mop:class-slots class) nil)
1605 (values (swank-mop:class-direct-slots class) t))
1606 (let ((slot-init-keywords
1607 (loop for slot in slots append
1608 (mapcar (lambda (initarg)
1609 (make-keyword-arg
1610 initarg
1611 initarg ; FIXME
1612 (swank-mop:slot-definition-initform slot)))
1613 (swank-mop:slot-definition-initargs slot))))
1614 (initialize-instance-keywords
1615 (applicable-methods-keywords #'initialize-instance
1616 (list class))))
1617 (return-from extra-keywords
1618 (values (append slot-init-keywords
1619 initialize-instance-keywords)
1620 allow-other-keys-p)))))))))
1621 (call-next-method))
1622
1623 (defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
1624 (multiple-value-bind (extra-keywords extra-aok)
1625 (apply #'extra-keywords form)
1626 ;; enrich the list of keywords with the extra keywords
1627 (when extra-keywords
1628 (setf (arglist.key-p decoded-arglist) t)
1629 (setf (arglist.keyword-args decoded-arglist)
1630 (remove-duplicates
1631 (append (arglist.keyword-args decoded-arglist)
1632 extra-keywords)
1633 :key #'keyword-arg.keyword)))
1634 (setf (arglist.allow-other-keys-p decoded-arglist)
1635 (or (arglist.allow-other-keys-p decoded-arglist) extra-aok)))
1636 decoded-arglist)
1637
1638 (defslimefun arglist-for-insertion (name)
1639 (with-buffer-syntax ()
1640 (let ((symbol (parse-symbol name)))
1641 (cond
1642 ((and symbol
1643 (valid-operator-name-p name))
1644 (let ((arglist (arglist symbol)))
1645 (etypecase arglist
1646 ((member :not-available)
1647 :not-available)
1648 (list
1649 (let ((decoded-arglist (decode-arglist arglist)))
1650 (enrich-decoded-arglist-with-extra-keywords decoded-arglist
1651 (list symbol))
1652 (decoded-arglist-to-template-string decoded-arglist
1653 *buffer-package*))))))
1654 (t
1655 :not-available)))))
1656
1657 (defvar *remove-keywords-alist*
1658 '((:test :test-not)
1659 (:test-not :test)))
1660
1661 (defun remove-actual-args (decoded-arglist actual-arglist)
1662 "Remove from DECODED-ARGLIST the arguments that have already been
1663 provided in ACTUAL-ARGLIST."
1664 (loop while (and actual-arglist
1665 (arglist.required-args decoded-arglist))
1666 do (progn (pop actual-arglist)
1667 (pop (arglist.required-args decoded-arglist))))
1668 (loop while (and actual-arglist
1669 (arglist.optional-args decoded-arglist))
1670 do (progn (pop actual-arglist)
1671 (pop (arglist.optional-args decoded-arglist))))
1672 (loop for keyword in actual-arglist by #'cddr
1673 for keywords-to-remove = (cdr (assoc keyword *remove-keywords-alist*))
1674 do (setf (arglist.keyword-args decoded-arglist)
1675 (remove-if (lambda (kw)
1676 (or (eql kw keyword)
1677 (member kw keywords-to-remove)))
1678 (arglist.keyword-args decoded-arglist)
1679 :key #'keyword-arg.keyword))))
1680
1681 (defgeneric form-completion (operator-form &rest argument-forms))
1682
1683 (defmethod form-completion (operator-form &rest argument-forms)
1684 (when (and (symbolp operator-form)
1685 (valid-operator-symbol-p operator-form))
1686 (let ((arglist (arglist operator-form)))
1687 (etypecase arglist
1688 ((member :not-available)
1689 :not-available)
1690 (list
1691 (let ((decoded-arglist (decode-arglist arglist)))
1692 (enrich-decoded-arglist-with-extra-keywords decoded-arglist
1693 (cons operator-form
1694 argument-forms))
1695 ;; get rid of formal args already provided
1696 (remove-actual-args decoded-arglist argument-forms)
1697 (return-from form-completion decoded-arglist))))))
1698 :not-available)
1699
1700 (defmethod form-completion ((operator-form (eql 'defmethod))
1701 &rest argument-forms)
1702 (when (and (listp argument-forms)
1703 (not (null argument-forms)) ;have generic function name
1704 (notany #'listp (rest argument-forms))) ;don't have arglist yet
1705 (let* ((gf-name (first argument-forms))
1706 (gf (and (or (symbolp gf-name)
1707 (and (listp gf-name)
1708 (eql (first gf-name) 'setf)))
1709 (fboundp gf-name)
1710 (fdefinition gf-name))))
1711 (when (typep gf 'generic-function)
1712 (let ((arglist (arglist gf)))
1713 (etypecase arglist
1714 ((member :not-available))
1715 (list
1716 (return-from form-completion
1717 (make-arglist :required-args (list arglist)
1718 :rest "body" :body-p t))))))))
1719 (call-next-method))
1720
1721 (defslimefun complete-form (form-string)
1722 "Read FORM-STRING in the current buffer package, then complete it
1723 by adding a template for the missing arguments."
1724 (with-buffer-syntax ()
1725 (handler-case
1726 (let ((form (read-from-string form-string)))
1727 (when (consp form)
1728 (let ((operator-form (first form))
1729 (argument-forms (rest form)))
1730 (let ((form-completion
1731 (apply #'form-completion operator-form argument-forms)))
1732 (unless (eql form-completion :not-available)
1733 (return-from complete-form
1734 (decoded-arglist-to-template-string form-completion
1735 *buffer-package*
1736 :prefix ""))))))
1737 :not-available)
1738 (reader-error (c)
1739 (declare (ignore c))
1740 :not-available))))
1741
1742
1743 ;;;; Recording and accessing results of computations
1744
1745 (defvar *record-repl-results* t
1746 "Non-nil means that REPL results are saved for later lookup.")
1747
1748 (defvar *object-to-presentation-id*
1749 (make-weak-key-hash-table :test 'eq)
1750 "Store the mapping of objects to numeric identifiers")
1751
1752 (defvar *presentation-id-to-object*
1753 (make-weak-value-hash-table :test 'eql)
1754 "Store the mapping of numeric identifiers to objects")
1755
1756 (defun clear-presentation-tables ()
1757 (clrhash *object-to-presentation-id*)
1758 (clrhash *presentation-id-to-object*))
1759
1760 (defvar *presentation-counter* 0 "identifier counter")
1761
1762 ;; XXX thread safety?
1763 (defun save-presented-object (object)
1764 "Save OBJECT and return the assigned id.
1765 If OBJECT was saved previously return the old id."
1766 (or (gethash object *object-to-presentation-id*)
1767 (let ((id (decf *presentation-counter*)))
1768 (setf (gethash id *presentation-id-to-object*) object)
1769 (setf (gethash object *object-to-presentation-id*) id)
1770 id)))
1771
1772 (defun lookup-presented-object (id)
1773 "Retrieve the object corresponding to ID.
1774 The secondary value indicates the absence of an entry."
1775 (gethash id *presentation-id-to-object*))
1776
1777 (defslimefun get-repl-result (id)
1778 "Get the result of the previous REPL evaluation with ID."
1779 (multiple-value-bind (object foundp) (lookup-presented-object id)
1780 (cond (foundp object)
1781 (t (error "Attempt to access unrecorded object (id ~D)." id)))))
1782
1783 (defslimefun clear-repl-results ()
1784 "Forget the results of all previous REPL evaluations."
1785 (clear-presentation-tables)
1786 t)
1787
1788
1789 ;;;; Evaluation
1790
1791 (defvar *pending-continuations* '()
1792 "List of continuations for Emacs. (thread local)")
1793
1794 (defun guess-buffer-package (string)
1795 "Return a package for STRING.
1796 Fall back to the the current if no such package exists."
1797 (or (guess-package-from-string string nil)
1798 *package*))
1799
1800 (defun eval-for-emacs (form buffer-package id)
1801 "Bind *BUFFER-PACKAGE* BUFFER-PACKAGE and evaluate FORM.
1802 Return the result to the continuation ID.
1803 Errors are trapped and invoke our debugger."
1804 (call-with-debugger-hook
1805 #'swank-debugger-hook
1806 (lambda ()
1807 (let (ok result)
1808 (unwind-protect
1809 (let ((*buffer-package* (guess-buffer-package buffer-package))
1810 (*buffer-readtable* (guess-buffer-readtable buffer-package))
1811 (*pending-continuations* (cons id *pending-continuations*)))
1812 (check-type *buffer-package* package)
1813 (check-type *buffer-readtable* readtable)
1814 ;; APPLY would be cleaner than EVAL.
1815 ;;(setq result (apply (car form) (cdr form)))
1816 (setq result (eval form))
1817 (finish-output)
1818 (run-hook *pre-reply-hook*)
1819 (setq ok t))
1820 (force-user-output)
1821 (send-to-emacs `(:return ,(current-thread)
1822 ,(if ok `(:ok ,result) '(:abort))
1823 ,id)))))))
1824
1825 (defvar *echo-area-prefix* "=> "
1826 "A prefix that `format-values-for-echo-area' should use.")
1827
1828 (defun format-values-for-echo-area (values)
1829 (with-buffer-syntax ()
1830 (let ((*print-readably* nil))
1831 (cond ((null values) "; No value")
1832 ((and (null (cdr values)) (integerp (car values)))
1833 (let ((i (car values)))
1834 (format nil "~A~D (#x~X, #o~O, #b~B)"
1835 *echo-area-prefix* i i i i)))
1836 (t (format nil "~A~{~S~^, ~}" *echo-area-prefix* values))))))
1837
1838 (defslimefun interactive-eval (string)
1839 (with-buffer-syntax ()
1840 (let ((values (multiple-value-list (eval (from-string string)))))
1841 (fresh-line)
1842 (finish-output)
1843 (format-values-for-echo-area values))))
1844
1845 (defslimefun eval-and-grab-output (string)
1846 (with-buffer-syntax ()
1847 (let* ((s (make-string-output-stream))
1848 (*standard-output* s)
1849 (values (multiple-value-list (eval (from-string string)))))
1850 (list (get-output-stream-string s)
1851 (format nil "~{~S~^~%~}" values)))))
1852
1853 ;;; XXX do we need this stuff? What is it good for?
1854 (defvar *slime-repl-advance-history* nil
1855 "In the dynamic scope of a single form typed at the repl, is set to nil to
1856 prevent the repl from advancing the history - * ** *** etc.")
1857
1858 (defvar *slime-repl-suppress-output* nil
1859 "In the dynamic scope of a single form typed at the repl, is set to nil to
1860 prevent the repl from printing the result of the evalation.")
1861
1862 (defvar *slime-repl-eval-hook-pass* (gensym "PASS")
1863 "Token to indicate that a repl hook declines to evaluate the form")
1864
1865 (defvar *slime-repl-eval-hooks* nil
1866 "A list of functions. When the repl is about to eval a form, first try running each of
1867 these hooks. The first hook which returns a value which is not *slime-repl-eval-hook-pass*
1868 is considered a replacement for calling eval. If there are no hooks, or all
1869 pass, then eval is used.")
1870
1871 (defslimefun repl-eval-hook-pass ()
1872 "call when repl hook declines to evaluate the form"
1873 (throw *slime-repl-eval-hook-pass* *slime-repl-eval-hook-pass*))
1874
1875 (defslimefun repl-suppress-output ()
1876 "In the dynamic scope of a single form typed at the repl, call to
1877 prevent the repl from printing the result of the evalation."
1878 (setq *slime-repl-suppress-output* t))
1879
1880 (defslimefun repl-suppress-advance-history ()
1881 "In the dynamic scope of a single form typed at the repl, call to
1882 prevent the repl from advancing the history - * ** *** etc."
1883 (setq *slime-repl-advance-history* nil))
1884
1885 (defun eval-region (string &optional package-update-p)
1886 "Evaluate STRING and return the result.
1887 If PACKAGE-UPDATE-P is non-nil, and evaluation causes a package
1888 change, then send Emacs an update."
1889 (unwind-protect
1890 (with-input-from-string (stream string)
1891 (let (- values)
1892 (loop
1893 (let ((form (read stream nil stream)))
1894 (when (eq form stream)
1895 (fresh-line)
1896 (finish-output)
1897 (return (values values -)))
1898 (setq - form)
1899 (if *slime-repl-eval-hooks*
1900 (setq values (run-repl-eval-hooks form))
1901 (setq values (multiple-value-list (eval form))))
1902 (finish-output)))))
1903 (when (and package-update-p (not (eq *package* *buffer-package*)))
1904 (send-to-emacs
1905 (list :new-package (package-name *package*)
1906 (package-string-for-prompt *package*))))))
1907
1908 (defun run-repl-eval-hooks (form)
1909 (loop for hook in *slime-repl-eval-hooks*
1910 for res = (catch *slime-repl-eval-hook-pass*
1911 (multiple-value-list (funcall hook form)))
1912 until (not (eq res *slime-repl-eval-hook-pass*))
1913 finally (return
1914 (if (eq res *slime-repl-eval-hook-pass*)
1915 (multiple-value-list (eval form))
1916 res))))
1917
1918 (defun package-string-for-prompt (package)
1919 "Return the shortest nickname (or canonical name) of PACKAGE."
1920 (princ-to-string
1921 (make-symbol
1922 (or (canonical-package-nickname package)
1923 (auto-abbreviated-package-name package)
1924 (shortest-package-nickname package)))))
1925
1926 (defun canonical-package-nickname (package)
1927 "Return the canonical package nickname, if any, of PACKAGE."
1928 (let ((name (cdr (assoc (package-name package) *canonical-package-nicknames*
1929 :test #'string=))))
1930 (and name (string name))))
1931
1932 (defun auto-abbreviated-package-name (package)
1933 "Return an abbreviated 'name' for PACKAGE.
1934
1935 N.B. this is not an actual package name or nickname."
1936 (when *auto-abbreviate-dotted-packages*
1937 (let ((last-dot (position #\. (package-name package) :from-end t)))
1938 (when last-dot (subseq (package-name package) (1+ last-dot))))))
1939
1940 (defun shortest-package-nickname (package)
1941 "Return the shortest nickname (or canonical name) of PACKAGE."
1942 (loop for name in (cons (package-name package) (package-nicknames package))
1943 for shortest = name then (if (< (length name) (length shortest))
1944 name
1945 shortest)
1946 finally (return shortest)))
1947
1948 (defslimefun interactive-eval-region (string)
1949 (with-buffer-syntax ()
1950 (format-values-for-echo-area (eval-region string))))
1951
1952 (defslimefun re-evaluate-defvar (form)
1953 (with-buffer-syntax ()
1954 (let ((form (read-from-string form)))
1955 (destructuring-bind (dv name &optional value doc) form
1956 (declare (ignore value doc))
1957 (assert (eq dv 'defvar))
1958 (makunbound name)
1959 (prin1-to-string (eval form))))))
1960
1961 (defvar *swank-pprint-bindings*
1962 `((*print-pretty* . t)
1963 (*print-level* . nil)
1964 (*print-length* . nil)
1965 (*print-circle* . t)
1966 (*print-gensym* . t)
1967 (*print-readably* . nil))
1968 "A list of variables bindings during pretty printing.
1969 Used by pprint-eval.")
1970
1971 (defun swank-pprint (list)
1972 "Bind some printer variables and pretty print each object in LIST."
1973 (with-buffer-syntax ()
1974 (with-bindings *swank-pprint-bindings*
1975 (cond ((null list) "; No value")
1976 (t (with-output-to-string (*standard-output*)
1977 (dolist (o list)
1978 (pprint o)
1979 (terpri))))))))
1980
1981 (defslimefun pprint-eval (string)
1982 (with-buffer-syntax ()
1983 (swank-pprint (multiple-value-list (eval (read-from-string string))))))
1984
1985 (defslimefun set-package (package)
1986 "Set *package* to PACKAGE.
1987 Return its name and the string to use in the prompt."
1988 (let ((p (setq *package* (guess-package-from-string package))))
1989 (list (package-name p) (package-string-for-prompt p))))
1990
1991 (defslimefun listener-eval (string)
1992 (clear-user-input)
1993 (with-buffer-syntax ()
1994 (let ((*slime-repl-suppress-output* :unset)
1995 (*slime-repl-advance-history* :unset))
1996 (multiple-value-bind (values last-form) (eval-region string t)
1997 (unless (or (and (eq values nil) (eq last-form nil))
1998 (eq *slime-repl-advance-history* nil))
1999 (setq *** ** ** * * (car values)
2000 /// // // / / values))
2001 (setq +++ ++ ++ + + last-form)
2002 (cond ((eq *slime-repl-suppress-output* t) '(:suppress-output))
2003 (*record-repl-results*
2004 `(:present ,(loop for x in values
2005 collect (cons (prin1-to-string x)
2006 (save-presented-object x)))))
2007 (t
2008 `(:values ,(mapcar #'prin1-to-string values))))))))
2009
2010 (defslimefun ed-in-emacs (&optional what)
2011 "Edit WHAT in Emacs.
2012
2013 WHAT can be:
2014 A pathname or a string,
2015 A list (PATHNAME-OR-STRING LINE [COLUMN]),
2016 A function name (symbol),
2017 NIL.
2018
2019 Returns true if it actually called emacs, or NIL if not."
2020 (flet ((pathname-or-string-p (thing)
2021 (or (pathnamep thing) (typep thing 'string))))
2022 (let ((target
2023 (cond ((and (listp what) (pathname-or-string-p (first what)))
2024 (cons (canonicalize-filename (car what)) (cdr what)))
2025 ((pathname-or-string-p what)
2026 (canonicalize-filename what))
2027 ((symbolp what) what)
2028 (t (return-from ed-in-emacs nil)))))
2029 (send-oob-to-emacs `(:ed ,target))
2030 t)))
2031
2032 (defslimefun value-for-editing (form)
2033 "Return a readable value of FORM for editing in Emacs.
2034 FORM is expected, but not required, to be SETF'able."
2035 ;; FIXME: Can we check FORM for setfability? -luke (12/Mar/2005)
2036 (with-buffer-syntax ()
2037 (prin1-to-string (eval (read-from-string form)))))
2038
2039 (defslimefun commit-edited-value (form value)
2040 "Set the value of a setf'able FORM to VALUE.
2041 FORM and VALUE are both strings from Emacs."
2042 (with-buffer-syntax ()
2043 (eval `(setf ,(read-from-string form)
2044 ,(read-from-string (concatenate 'string "`" value))))
2045 t))
2046
2047 (defun background-message (format-string &rest args)
2048 "Display a message in Emacs' echo area.
2049
2050 Use this function for informative messages only. The message may even
2051 be dropped, if we are too busy with other things."
2052 (when *emacs-connection*
2053 (send-to-emacs `(:background-message
2054 ,(apply #'format nil format-string args)))))
2055
2056
2057 ;;;; Debugger
2058
2059 (defun swank-debugger-hook (condition hook)
2060 "Debugger function for binding *DEBUGGER-HOOK*.
2061 Sends a message to Emacs declaring that the debugger has been entered,
2062 then waits to handle further requests from Emacs. Eventually returns
2063 after Emacs causes a restart to be invoked."
2064 (declare (ignore hook))
2065 (cond (*emacs-connection*
2066 (debug-in-emacs condition))
2067 ((default-connection)
2068 (with-connection ((default-connection))
2069 (debug-in-emacs condition)))))
2070
2071 (defvar *global-debugger* t
2072 "Non-nil means the Swank debugger hook will be installed globally.")
2073
2074 (add-hook *new-connection-hook* 'install-debugger)
2075 (defun install-debugger (connection)
2076 (declare (ignore connection))
2077 (when *global-debugger*
2078 (install-debugger-globally #'swank-debugger-hook)))
2079
2080 ;;;;; Debugger loop
2081 ;;;
2082 ;;; These variables are dynamically bound during debugging.
2083 ;;;
2084 (defvar *swank-debugger-condition* nil
2085 "The condition being debugged.")
2086
2087 (defvar *sldb-level* 0
2088 "The current level of recursive debugging.")
2089
2090 (defvar *sldb-initial-frames* 20
2091 "The initial number of backtrace frames to send to Emacs.")
2092
2093 (defvar *sldb-restarts* nil
2094 "The list of currenlty active restarts.")
2095
2096 (defvar *sldb-stepping-p* nil
2097 "True when during execution of a stepp command.")
2098
2099 (defun debug-in-emacs (condition)
2100 (let ((*swank-debugger-condition* condition)
2101 (*sldb-restarts* (compute-restarts condition))
2102 (*package* (or (and (boundp '*buffer-package*)
2103 (symbol-value '*buffer-package*))
2104 *package*))
2105 (*sldb-level* (1+ *sldb-level*))
2106 (*sldb-stepping-p* nil)
2107 (*swank-state-stack* (cons :swank-debugger-hook *swank-state-stack*)))
2108 (force-user-output)
2109 (with-bindings *sldb-printer-bindings*
2110 (call-with-debugging-environment
2111 (lambda () (sldb-loop *sldb-level*))))))
2112
2113 (defun sldb-loop (level)
2114 (unwind-protect
2115 (catch 'sldb-enter-default-debugger
2116 (send-to-emacs
2117 (list* :debug (current-thread) level
2118 (debugger-info-for-emacs 0 *sldb-initial-frames*)))
2119 (loop (catch 'sldb-loop-catcher
2120 (with-simple-restart (abort "Return to sldb level ~D." level)
2121 (send-to-emacs (list :debug-activate (current-thread)
2122 level))
2123 (handler-bind ((sldb-condition #'handle-sldb-condition))
2124 (read-from-emacs))))))
2125 (send-to-emacs `(:debug-return
2126 ,(current-thread) ,level ,*sldb-stepping-p*))))
2127
2128 (defun handle-sldb-condition (condition)
2129 "Handle an internal debugger condition.
2130 Rather than recursively debug the debugger (a dangerous idea!), these
2131 conditions are simply reported."
2132 (let ((real-condition (original-condition condition)))
2133 (send-to-emacs `(:debug-condition ,(current-thread)
2134 ,(princ-to-string real-condition))))
2135 (throw 'sldb-loop-catcher nil))
2136
2137 (defun safe-condition-message (condition)
2138 "Safely print condition to a string, handling any errors during
2139 printing."
2140 (let ((*print-pretty* t))
2141 (handler-case
2142 (format-sldb-condition condition)
2143 (error (cond)
2144 ;; Beware of recursive errors in printing, so only use the condition
2145 ;; if it is printable itself:
2146 (format nil "Unable to display error condition~@[: ~A~]"
2147 (ignore-errors (princ-to-string cond)))))))
2148
2149 (defun debugger-condition-for-emacs ()
2150 (list (safe-condition-message *swank-debugger-condition*)
2151 (format nil " [Condition of type ~S]"
2152 (type-of *swank-debugger-condition*))
2153 (condition-references *swank-debugger-condition*)
2154 (condition-extras *swank-debugger-condition*)))
2155
2156 (defun format-restarts-for-emacs ()
2157 "Return a list of restarts for *swank-debugger-condition* in a
2158 format suitable for Emacs."
2159 (loop for restart in *sldb-restarts*
2160 collect (list (princ-to-string (restart-name restart))
2161 (princ-to-string restart))))
2162
2163 (defun frame-for-emacs (n frame)
2164 (let* ((label (format nil " ~2D: " n))
2165 (string (with-output-to-string (stream)
2166 (princ label stream)
2167 (print-frame frame stream))))
2168 (subseq string (length label))))
2169
2170 ;;;;; SLDB entry points
2171
2172 (defslimefun sldb-break-with-default-debugger ()
2173 "Invoke the default debugger by returning from our debugger-loop."
2174 (throw 'sldb-enter-default-debugger nil))
2175
2176 (defslimefun backtrace (start end)
2177 "Return a list ((I FRAME) ...) of frames from START to END.
2178 I is an integer describing and FRAME a string."
2179 (loop for frame in (compute-backtrace start end)
2180 for i from start
2181 collect (list i (frame-for-emacs i frame))))
2182
2183 (defslimefun debugger-info-for-emacs (start end)
2184 "Return debugger state, with stack frames from START to END.
2185 The result is a list:
2186 (condition ({restart}*) ({stack-frame}*) (cont*))
2187 where
2188 condition ::= (description type [extra])
2189 restart ::= (name description)
2190 stack-frame ::= (number description)
2191 extra ::= (:references and other random things)
2192 cont ::= continutation
2193 condition---a pair of strings: message, and type. If show-source is
2194 not nil it is a frame number for which the source should be displayed.
2195
2196 restart---a pair of strings: restart name, and description.
2197
2198 stack-frame---a number from zero (the top), and a printed
2199 representation of the frame's call.
2200
2201 continutation---the id of a pending Emacs continuation.
2202
2203 Below is an example return value. In this case the condition was a
2204 division by zero (multi-line description), and only one frame is being
2205 fetched (start=0, end=1).
2206
2207 ((\"Arithmetic error DIVISION-BY-ZERO signalled.
2208 Operation was KERNEL::DIVISION, operands (1 0).\"
2209 \"[Condition of type DIVISION-BY-ZERO]\")
2210 ((\"ABORT\" \"Return to Slime toplevel.\")
2211 (\"ABORT\" \"Return to Top-Level.\"))
2212 ((0 \"(KERNEL::INTEGER-/-INTEGER 1 0)\"))
2213 (4))"
2214 (list (debugger-condition-for-emacs)
2215 (format-restarts-for-emacs)
2216 (backtrace start end)
2217 *pending-continuations*))
2218
2219 (defun nth-restart (index)
2220 (nth index *sldb-restarts*))
2221
2222 (defslimefun invoke-nth-restart (index)
2223 (invoke-restart-interactively (nth-restart index)))
2224
2225 (defslimefun sldb-abort ()
2226 (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))
2227
2228 (defslimefun sldb-continue ()
2229 (continue))
2230
2231 (defslimefun throw-to-toplevel ()
2232 "Invoke the ABORT-REQUEST restart abort an RPC from Emacs.
2233 If we are not evaluating an RPC then ABORT instead."
2234 (let ((restart (find-restart 'abort-request)))
2235 (cond (restart (invoke-restart restart))
2236 (t
2237 ;; If we get here then there was no catch. Try aborting as
2238 ;; a fallback. That makes the 'q' command in SLDB safer to
2239 ;; use with threads.
2240 (abort)))))
2241
2242 (defslimefun invoke-nth-restart-for-emacs (sldb-level n)
2243 "Invoke the Nth available restart.
2244 SLDB-LEVEL is the debug level when the request was made. If this
2245 has changed, ignore the request."
2246 (when (= sldb-level *sldb-level*)
2247 (invoke-nth-restart n)))
2248
2249 (defun wrap-sldb-vars (form)
2250 `(let ((*sldb-level* ,*sldb-level*))
2251 ,form))
2252
2253 (defslimefun eval-string-in-frame (string index)
2254 (to-string (eval-in-frame (wrap-sldb-vars (from-string string))
2255 index)))
2256
2257 (defslimefun pprint-eval-string-in-frame (string index)
2258 (swank-pprint
2259 (multiple-value-list
2260 (eval-in-frame (wrap-sldb-vars (from-string string)) index))))
2261
2262 (defslimefun frame-locals-for-emacs (index)
2263 "Return a property list ((&key NAME ID VALUE) ...) describing
2264 the local variables in the frame INDEX."
2265 (mapcar (lambda (frame-locals)
2266 (destructuring-bind (&key name id value) frame-locals
2267 (list :name (prin1-to-string name) :id id
2268 :value (to-string value))))
2269 (frame-locals index)))
2270
2271 (defslimefun frame-catch-tags-for-emacs (frame-index)
2272 (mapcar #'to-string (frame-catch-tags frame-index)))
2273
2274 (defslimefun sldb-disassemble (index)
2275 (with-output-to-string (*standard-output*)
2276 (disassemble-frame index)))
2277
2278 (defslimefun sldb-return-from-frame (index string)
2279 (let ((form (from-string string)))
2280 (to-string (multiple-value-list (return-from-frame index form)))))
2281
2282 (defslimefun sldb-break (name)
2283 (with-buffer-syntax ()
2284 (sldb-break-at-start (read-from-string name))))
2285
2286 (defslimefun sldb-step (frame)
2287 (cond ((find-restart 'continue)
2288 (activate-stepping frame)
2289 (setq *sldb-stepping-p* t)
2290 (continue))
2291 (t
2292 (error "No continue restart."))))
2293
2294
2295 ;;;; Compilation Commands.
2296
2297 (defvar *compiler-notes* '()
2298 "List of compiler notes for the last compilation unit.")
2299
2300 (defun clear-compiler-notes ()
2301 (setf *compiler-notes* '()))
2302
2303 (defun canonicalize-filename (filename)
2304 (namestring (truename filename)))
2305
2306 (defslimefun compiler-notes-for-emacs ()
2307 "Return the list of compiler notes for the last compilation unit."
2308 (reverse *compiler-notes*))
2309
2310 (defun measure-time-interval (fn)
2311 "Call FN and return the first return value and the elapsed time.
2312 The time is measured in microseconds."
2313 (declare (type function fn))
2314 (let ((before (get-internal-real-time)))
2315 (values
2316 (funcall fn)
2317 (* (- (get-internal-real-time) before)
2318 (/ 1000000 internal-time-units-per-second)))))
2319
2320 (defun record-note-for-condition (condition)
2321 "Record a note for a compiler-condition."
2322 (push (make-compiler-note condition) *compiler-notes*))
2323
2324 (defun make-compiler-note (condition)
2325 "Make a compiler note data structure from a compiler-condition."
2326 (declare (type compiler-condition condition))
2327 (list* :message (message condition)
2328 :severity (severity condition)
2329 :location (location condition)
2330 :references (references condition)
2331 (let ((s (short-message condition)))
2332 (if s (list :short-message s)))))
2333
2334 (defun swank-compiler (function)
2335 (clear-compiler-notes)
2336 (with-simple-restart (abort "Abort SLIME compilation.")
2337 (multiple-value-bind (result usecs)
2338 (handler-bind ((compiler-condition #'record-note-for-condition))
2339 (measure-time-interval function))
2340 (list (to-string result)
2341 (format nil "~,2F" (/ usecs 1000000.0))))))
2342
2343 (defslimefun compile-file-for-emacs (filename load-p &optional external-format)
2344 "Compile FILENAME and, when LOAD-P, load the result.
2345 Record compiler notes signalled as `compiler-condition's."
2346 (with-buffer-syntax ()
2347 (let ((*compile-print* nil))
2348 (swank-compiler (lambda () (swank-compile-file filename load-p
2349 external-format))))))
2350
2351 (defslimefun compile-string-for-emacs (string buffer position directory)
2352 "Compile STRING (exerpted from BUFFER at POSITION).
2353 Record compiler notes signalled as `compiler-condition's."
2354 (with-buffer-syntax ()
2355 (swank-compiler
2356 (lambda ()
2357 (let ((*compile-print* nil) (*compile-verbose* t))
2358 (swank-compile-string string :buffer buffer :position position
2359 :directory directory))))))
2360
2361 (defslimefun operate-on-system-for-emacs (system-name operation &rest keywords)
2362 "Compile and load SYSTEM using ASDF.
2363 Record compiler notes signalled as `compiler-condition's."
2364 (swank-compiler
2365 (lambda ()
2366 (apply #'operate-on-system system-name operation keywords))))
2367
2368 (defun asdf-central-registry ()
2369 (when (find-package :asdf)
2370 (symbol-value (find-symbol (string :*central-registry*) :asdf))))
2371
2372 (defslimefun list-all-systems-in-central-registry ()
2373 "Returns a list of all systems in ASDF's central registry."
2374 (delete-duplicates
2375 (loop for dir in (asdf-central-registry)
2376 for defaults = (eval dir)
2377 when defaults
2378 nconc (mapcar #'file-namestring
2379 (directory
2380 (make-pathname :defaults defaults
2381 :version :newest
2382 :type "asd"
2383 :name :wild
2384 :case :local))))
2385 :test #'string=))
2386
2387 (defun file-newer-p (new-file old-file)
2388 "Returns true if NEW-FILE is newer than OLD-FILE."
2389 (> (file-write-date new-file) (file-write-date old-file)))
2390
2391 (defun requires-compile-p (source-file)
2392 (let ((fasl-file (probe-file (compile-file-pathname source-file))))
2393 (or (not fasl-file)
2394 (file-newer-p source-file fasl-file))))
2395
2396 (defslimefun compile-file-if-needed (filename loadp)
2397 (cond ((requires-compile-p filename)
2398 (compile-file-for-emacs filename loadp))
2399 (loadp
2400 (load (compile-file-pathname filename))
2401 nil)))
2402
2403
2404 ;;;; Loading
2405
2406 (defslimefun load-file (filename)
2407 (to-string (load filename)))
2408
2409 (defslimefun load-file-set-package (filename &optional package)
2410 (load-file filename)
2411 (if package
2412 (set-package package)))
2413
2414
2415 ;;;; Macroexpansion
2416
2417 (defvar *macroexpand-printer-bindings*
2418 '((*print-circle* . nil)
2419 (*print-pretty* . t)
2420 (*print-escape* . t)
2421 (*print-level* . nil)
2422 (*print-length* . nil)))
2423
2424 (defun apply-macro-expander (expander string)
2425 (declare (type function expander))
2426 (with-buffer-syntax ()
2427 (with-bindings *macroexpand-printer-bindings*
2428 (prin1-to-string (funcall expander (from-string string))))))
2429
2430 (defslimefun swank-macroexpand-1 (string)
2431 (apply-macro-expander #'macroexpand-1 string))
2432
2433 (defslimefun swank-macroexpand (string)
2434 (apply-macro-expander #'macroexpand string))
2435
2436 (defslimefun swank-macroexpand-all (string)
2437 (apply-macro-expander #'macroexpand-all string))
2438
2439 (defslimefun swank-compiler-macroexpand-1 (string)
2440 (apply-macro-expander #'compiler-macroexpand-1 string))
2441
2442 (defslimefun swank-compiler-macroexpand (string)
2443 (apply-macro-expander #'compiler-macroexpand string))
2444
2445 (defslimefun disassemble-symbol (name)
2446 (with-buffer-syntax ()
2447 (with-output-to-string (*standard-output*)
2448 (let ((*print-readably* nil))
2449 (disassemble (fdefinition (from-string name)))))))
2450
2451
2452 ;;;; Basic completion
2453
2454 (defslimefun completions (string default-package-name)
2455 "Return a list of completions for a symbol designator STRING.
2456
2457 The result is the list (COMPLETION-SET
2458 COMPLETED-PREFIX). COMPLETION-SET is the list of all matching
2459 completions, and COMPLETED-PREFIX is the best (partial)
2460 completion of the input string.
2461
2462 If STRING is package qualified the result list will also be
2463 qualified. If string is non-qualified the result strings are
2464 also not qualified and are considered relative to
2465 DEFAULT-PACKAGE-NAME.
2466
2467 The way symbols are matched depends on the symbol designator's
2468 format. The cases are as follows:
2469 FOO - Symbols with matching prefix and accessible in the buffer package.
2470 PKG:FOO - Symbols with matching prefix and external in package PKG.
2471 PKG::FOO - Symbols with matching prefix and accessible in package PKG."
2472 (let ((completion-set (completion-set string default-package-name
2473 #'compound-prefix-match)))
2474 (list completion-set (longest-completion completion-set))))
2475
2476 (defslimefun simple-completions (string default-package-name)
2477 "Return a list of completions for a symbol designator STRING."
2478 (let ((completion-set (completion-set string default-package-name
2479 #'prefix-match-p)))
2480 (list completion-set (longest-common-prefix completion-set))))
2481
2482 ;;;;; Find completion set
2483
2484 (defun completion-set (string default-package-name matchp)
2485 "Return the set of completion-candidates as strings."
2486 (multiple-value-bind (name package-name package internal-p)
2487 (parse-completion-arguments string default-package-name)
2488 (let* ((symbols (and package
2489 (find-matching-symbols name
2490 package
2491 (and (not internal-p)
2492 package-name)
2493 matchp)))
2494 (packs (and (not package-name)
2495 (find-matching-packages name matchp)))
2496 (converter (output-case-converter name))
2497 (strings
2498 (mapcar converter
2499 (nconc (mapcar #'symbol-name symbols) packs))))
2500 (format-completion-set strings internal-p package-name))))
2501
2502 (defun find-matching-symbols (string package external test)
2503 "Return a list of symbols in PACKAGE matching STRING.
2504 TEST is called with two strings. If EXTERNAL is true, only external
2505 symbols are returned."
2506 (let ((completions '())
2507 (converter (output-case-converter string)))
2508 (flet ((symbol-matches-p (symbol)
2509 (and (or (not external)
2510 (symbol-external-p symbol package))
2511 (funcall test string
2512 (funcall converter (symbol-name symbol))))))
2513 (do-symbols (symbol package)
2514 (when (symbol-matches-p symbol)
2515 (push symbol completions))))
2516 (remove-duplicates completions)))
2517
2518 (defun symbol-external-p (symbol &optional (package (symbol-package symbol)))
2519 "True if SYMBOL is external in PACKAGE.
2520 If PACKAGE is not specified, the home package of SYMBOL is used."
2521 (and package
2522 (eq (nth-value 1 (find-symbol (symbol-name symbol) package))
2523 :external)))
2524
2525 (defun find-matching-packages (name matcher)
2526 "Return a list of package names matching NAME with MATCHER.
2527 MATCHER is a two-argument predicate."
2528 (let ((to-match (string-upcase name)))
2529 (remove-if-not (lambda (x) (funcall matcher to-match x))
2530 (mapcar (lambda (pkgname)
2531 (concatenate 'string pkgname ":"))
2532 (loop for package in (list-all-packages)
2533 collect (package-name package)
2534 append (package-nicknames package))))))
2535
2536 (defun parse-completion-arguments (string default-package-name)
2537 "Parse STRING as a symbol designator.
2538 Return these values:
2539 SYMBOL-NAME
2540 PACKAGE-NAME, or nil if the designator does not include an explicit package.
2541 PACKAGE, the package to complete in
2542 INTERNAL-P, if the symbol is qualified with `::'."
2543 (multiple-value-bind (name package-name internal-p)
2544 (tokenize-symbol string)
2545 (let ((package (carefully-find-package package-name default-package-name)))
2546 (values name package-name package internal-p))))
2547
2548 (defun carefully-find-package (name default-package-name)
2549 "Find the package with name NAME, or DEFAULT-PACKAGE-NAME, or the
2550 *buffer-package*. NAME and DEFAULT-PACKAGE-NAME can be nil."
2551 (let ((string (cond ((equal name "") "KEYWORD")
2552 (t (or name default-package-name)))))
2553 (if string
2554 (guess-package-from-string string nil)
2555 *buffer-package*)))
2556
2557 ;;;;; Format completion results
2558 ;;;
2559 ;;; We try to format results in the case as inputs. If you complete
2560 ;;; `FOO' then your result should include `FOOBAR' rather than
2561 ;;; `foobar'.
2562
2563 (defun format-completion-set (strings internal-p package-name)
2564 "Format a set of completion strings.
2565 Returns a list of completions with package qualifiers if needed."
2566 (mapcar (lambda (string)
2567 (format-completion-result string internal-p package-name))
2568 (sort strings #'string<)))
2569
2570 (defun format-completion-result (string internal-p package-name)
2571 (let ((prefix (cond (internal-p (format nil "~A::" package-name))
2572 (package-name (format nil "~A:" package-name))
2573 (t ""))))
2574 (values (concatenate 'string prefix string)
2575 (length prefix))))
2576
2577 (defun output-case-converter (input)
2578 "Return a function to case convert strings for output.
2579 INPUT is used to guess the preferred case."
2580 (ecase (readtable-case *readtable*)
2581 (:upcase (if (some #'lower-case-p input) #'string-downcase #'identity))
2582 (:invert (lambda (output)
2583 (multiple-value-bind (lower upper) (determine-case output)
2584 (cond ((and lower upper) output)
2585 (lower (string-upcase output))
2586 (upper (string-downcase output))
2587 (t output)))))
2588 (:downcase (if (some #'upper-case-p input) #'string-upcase #'identity))
2589 (:preserve #'identity)))
2590
2591 (defun determine-case (string)
2592 "Return two booleans LOWER and UPPER indicating whether STRING
2593 contains lower or upper case characters."
2594 (values (some #'lower-case-p string)
2595 (some #'upper-case-p string)))
2596
2597
2598 ;;;;; Compound-prefix matching
2599
2600 (defun compound-prefix-match (prefix target)
2601 "Return true if PREFIX is a compound-prefix of TARGET.
2602 Viewing each of PREFIX and TARGET as a series of substrings delimited
2603 by hyphens, if each substring of PREFIX is a prefix of the
2604 corresponding substring in TARGET then we call PREFIX a
2605 compound-prefix of TARGET.
2606
2607 Examples:
2608 \(compound-prefix-match \"foo\" \"foobar\") => t
2609 \(compound-prefix-match \"m--b\" \"multiple-value-bind\") => t
2610 \(compound-prefix-match \"m-v-c\" \"multiple-value-bind\") => NIL"
2611 (declare (type simple-string prefix target))
2612 (loop for ch across prefix
2613 with tpos = 0
2614 always (and (< tpos (length target))
2615 (if (char= ch #\-)
2616 (setf tpos (position #\- target :start tpos))
2617 (char= ch (aref target tpos))))
2618 do (incf tpos)))
2619
2620 (defun prefix-match-p (prefix string)
2621 "Return true if PREFIX is a prefix of STRING."
2622 (not (mismatch prefix string :end2 (min (length string) (length prefix)))))
2623
2624
2625 ;;;;; Extending the input string by completion
2626
2627 (defun longest-completion (completions)
2628 "Return the longest prefix for all COMPLETIONS.
2629 COMPLETIONS is a list of strings."
2630 (untokenize-completion
2631 (mapcar #'longest-common-prefix
2632 (transpose-lists (mapcar #'tokenize-completion completions)))))
2633
2634 (defun tokenize-completion (string)
2635 "Return all substrings of STRING delimited by #\-."
2636 (loop with end
2637 for start = 0 then (1+ end)
2638 until (> start (length string))
2639 do (setq end (or (position #\- string :start start) (length string)))
2640 collect (subseq string start end)))
2641
2642 (defun untokenize-completion (tokens)
2643 (format nil "~{~A~^-~}" tokens))
2644
2645 (defun longest-common-prefix (strings)
2646 "Return the longest string that is a common prefix of STRINGS."
2647 (if (null strings)
2648 ""
2649 (flet ((common-prefix (s1 s2)
2650 (let ((diff-pos (mismatch s1 s2)))
2651 (if diff-pos (subseq s1 0 diff-pos) s1))))
2652 (reduce #'common-prefix strings))))
2653
2654 (defun transpose-lists (lists)
2655 "Turn a list-of-lists on its side.
2656 If the rows are of unequal length, truncate uniformly to the shortest.
2657
2658 For example:
2659 \(transpose-lists '((ONE TWO THREE) (1 2)))
2660 => ((ONE 1) (TWO 2))"
2661 (cond ((null lists) '())
2662 ((some #'null lists) '())
2663 (t (cons (mapcar #'car lists)
2664 (transpose-lists (mapcar #'cdr lists))))))
2665
2666
2667 ;;;;; Completion Tests
2668
2669 (defpackage :swank-completion-test
2670 (:use))
2671
2672 (let ((*readtable* (copy-readtable *readtable*))
2673 (p (find-package :swank-completion-test)))
2674 (intern "foo" p)
2675 (intern "Foo" p)
2676 (intern "FOO" p)
2677 (setf (readtable-case *readtable*) :invert)
2678 (flet ((names (prefix)
2679 (sort (mapcar #'symbol-name
2680 (find-matching-symbols prefix p nil #'prefix-match-p))
2681 #'string<)))
2682 (assert (equal '("FOO") (names "f")))
2683 (assert (equal '("Foo" "foo") (names "F")))
2684 (assert (equal '("Foo") (names "Fo")))
2685 (assert (equal '("foo") (names "FO")))))
2686
2687 ;;;; Fuzzy completion
2688
2689 (defslimefun fuzzy-completions (string default-package-name &optional limit)
2690 "Return an (optionally limited to LIMIT best results) list of
2691 fuzzy completions for a symbol designator STRING. The list will
2692 be sorted by score, most likely match first.
2693
2694 The result is a list of completion objects, where a completion
2695 object is:
2696 (COMPLETED-STRING SCORE (&rest CHUNKS) FLAGS)
2697 where a CHUNK is a description of a matched string of characters:
2698 (OFFSET STRING)
2699 and FLAGS is a list of keywords describing properties of the symbol.
2700 For example, the top result for completing \"mvb\" in a package
2701 that uses COMMON-LISP would be something like:
2702 (\"multiple-value-bind\" 42.391666 ((0 \"mul\") (9 \"v\") (15 \"b\"))
2703 (:FBOUNDP :MACRO))
2704
2705 If STRING is package qualified the result list will also be
2706 qualified. If string is non-qualified the result strings are
2707 also not qualified and are considered relative to
2708 DEFAULT-PACKAGE-NAME.
2709
2710 Which symbols are candidates for matching depends on the symbol
2711 designator's format. The cases are as follows:
2712 FOO - Symbols accessible in the buffer package.
2713 PKG:FOO - Symbols external in package PKG.
2714 PKG::FOO - Symbols accessible in package PKG."
2715 (fuzzy-completion-set string default-package-name limit))
2716
2717 (defun convert-fuzzy-completion-result (result converter
2718 internal-p package-name)
2719 "Converts a result from the fuzzy completion core into
2720 something that emacs is expecting. Converts symbols to strings,
2721 fixes case issues, and adds information describing if the symbol
2722 is :bound, :fbound, a :class, a :macro, a :generic-function,
2723 a :special-operator, or a :package."
2724 (destructuring-bind (symbol-or-name score chunks) result
2725 (multiple-value-bind (name added-length)
2726 (format-completion-result
2727 (funcall converter
2728 (if (symbolp symbol-or-name)
2729 (symbol-name symbol-or-name)
2730 symbol-or-name))
2731 internal-p package-name)
2732 (list name score
2733 (mapcar
2734 #'(lambda (chunk)
2735 ;; fix up chunk positions to account for possible
2736 ;; added package identifier
2737 (list (+ added-length (first chunk))
2738 (second chunk)))
2739 chunks)
2740 (loop for flag in '(:boundp :fboundp :generic-function
2741 :class :macro :special-operator
2742 :package)
2743 if (if (symbolp symbol-or-name)
2744 (case flag
2745 (:boundp (boundp symbol-or-name))
2746 (:fboundp (fboundp symbol-or-name))
2747 (:class (find-class symbol-or-name nil))
2748 (:macro (macro-function symbol-or-name))
2749 (:special-operator
2750 (special-operator-p symbol-or-name))
2751 (:generic-function
2752 (typep (ignore-errors (fdefinition symbol-or-name))
2753 'generic-function)))
2754 (case flag
2755 (:package (stringp symbol-or-name)
2756 ;; KLUDGE: depends on internal
2757 ;; knowledge that packages are
2758 ;; brought up from the bowels of
2759 ;; the completion algorithm as
2760 ;; strings!
2761 )))
2762 collect flag)))))
2763
2764 (defun fuzzy-completion-set (string default-package-name &optional limit)
2765 "Prepares list of completion obajects, sorted by SCORE, of fuzzy
2766 completions of STRING in DEFAULT-PACKAGE-NAME. If LIMIT is set,
2767 only the top LIMIT results will be returned."
2768 (multiple-value-bind (name package-name package internal-p)
2769 (parse-completion-arguments string default-package-name)
2770 (let* ((symbols (and package
2771 (fuzzy-find-matching-symbols name
2772 package
2773 (and (not internal-p)
2774 package-name))))
2775 (packs (and (not package-name)
2776 (fuzzy-find-matching-packages name)))
2777 (converter (output-case-converter name))
2778 (results
2779 (sort (mapcar #'(lambda (result)
2780 (convert-fuzzy-completion-result
2781 result converter internal-p package-name))
2782 (nconc symbols packs))
2783 #'> :key #'second)))
2784 (when (and limit
2785 (> limit 0)
2786 (< limit (length results)))
2787 (setf (cdr (nthcdr (1- limit) results)) nil))
2788 results)))
2789
2790 (defun fuzzy-find-matching-symbols (string package external)
2791 "Return a list of symbols in PACKAGE matching STRING using the
2792 fuzzy completion algorithm. If EXTERNAL is true, only external
2793 symbols are returned."
2794 (let ((completions '())
2795 (converter (output-case-converter string)))
2796 (flet ((symbol-match (symbol)
2797 (and (or (not external)
2798 (symbol-external-p symbol package))
2799 (compute-highest-scoring-completion
2800 string (funcall converter (symbol-name symbol)) #'char=))))
2801 (do-symbols (symbol package)
2802 (if (string= "" string)
2803 (when (or (and external (symbol-external-p symbol package))
2804 (not external))
2805 (push (list symbol 0.0 (list (list 0 ""))) completions))
2806 (multiple-value-bind (result score) (symbol-match symbol)
2807 (when result
2808 (push (list symbol score result) completions))))))
2809 (remove-duplicates completions :key #'first)))
2810
2811 (defun fuzzy-find-matching-packages (name)
2812 "Return a list of package names matching NAME using the fuzzy
2813 completion algorithm."
2814 (let ((converter (output-case-converter name)))
2815 (loop for package in (list-all-packages)
2816 for package-name = (concatenate 'string
2817 (funcall converter
2818 (package-name package))
2819 ":")
2820 for (result score) = (multiple-value-list
2821 (compute-highest-scoring-completion
2822 name package-name #'char=))
2823 if result collect (list package-name score result))))
2824
2825 (defslimefun fuzzy-completion-selected (original-string completion)
2826 "This function is called by Slime when a fuzzy completion is
2827 selected by the user. It is for future expansion to make
2828 testing, say, a machine learning algorithm for completion scoring
2829 easier.
2830
2831 ORIGINAL-STRING is the string the user completed from, and
2832 COMPLETION is the completion object (see docstring for
2833 SWANK:FUZZY-COMPLETIONS) corresponding to the completion that the
2834 user selected."
2835 (declare (ignore original-string completion))
2836 nil)
2837
2838 ;;;;; Fuzzy completion core
2839
2840 (defparameter *fuzzy-recursion-soft-limit* 30
2841 "This is a soft limit for recursion in
2842 RECURSIVELY-COMPUTE-MOST-COMPLETIONS. Without this limit,
2843 completing a string such as \"ZZZZZZ\" with a symbol named
2844 \"ZZZZZZZZZZZZZZZZZZZZZZZ\" will result in explosive recursion to
2845 find all the ways it can match.
2846
2847 Most natural language searches and symbols do not have this
2848 problem -- this is only here as a safeguard.")
2849
2850 (defun compute-highest-scoring-completion (short full test)
2851 "Finds the highest scoring way to complete the abbreviation
2852 SHORT onto the string FULL, using TEST as a equality function for
2853 letters. Returns two values: The first being the completion
2854 chunks of the high scorer, and the second being the score."
2855 (let* ((scored-results
2856 (mapcar #'(lambda (result)
2857 (cons (score-completion result short full) result))
2858 (compute-most-completions short full test)))
2859 (winner (first (sort scored-results #'> :key #'first))))
2860 (values (rest winner) (first winner))))
2861
2862 (defun compute-most-completions (short full test)
2863 "Finds most possible ways to complete FULL with the letters in SHORT.
2864 Calls RECURSIVELY-COMPUTE-MOST-COMPLETIONS recursively. Returns
2865 a list of (&rest CHUNKS), where each CHUNKS is a description of
2866 how a completion matches."
2867 (let ((*all-chunks* nil))
2868 (declare (special *all-chunks*))
2869 (recursively-compute-most-completions short full test 0 0 nil nil nil t)
2870 *all-chunks*))
2871
2872 (defun recursively-compute-most-completions
2873 (short full test
2874 short-index initial-full-index
2875 chunks current-chunk current-chunk-pos
2876 recurse-p)
2877 "Recursively (if RECURSE-P is true) find /most/ possible ways
2878 to fuzzily map the letters in SHORT onto FULL, with TEST being a
2879 function to determine if two letters match.
2880
2881 A chunk is a list of elements that have matched consecutively.
2882 When consecutive matches stop, it is coerced into a string,
2883 paired with the starting position of the chunk, and pushed onto
2884 CHUNKS.
2885
2886 Whenever a letter matches, if RECURSE-P is true,
2887 RECURSIVELY-COMPUTE-MOST-COMPLETIONS calls itself with a position
2888 one index ahead, to find other possibly higher scoring
2889 possibilities. If there are less than
2890 *FUZZY-RECURSION-SOFT-LIMIT* results in *ALL-CHUNKS* currently,
2891 this call will also recurse.
2892
2893 Once a word has been completely matched, the chunks are pushed
2894 onto the special variable *ALL-CHUNKS* and the function returns."
2895 (declare (special *all-chunks*))
2896 (flet ((short-cur ()
2897 "Returns the next letter from the abbreviation, or NIL
2898 if all have been used."
2899 (if (= short-index (length short))
2900 nil
2901 (aref short short-index)))
2902 (add-to-chunk (char pos)
2903 "Adds the CHAR at POS in FULL to the current chunk,
2904 marking the start position if it is empty."
2905 (unless current-chunk
2906 (setf current-chunk-pos pos))
2907 (push char current-chunk))
2908 (collect-chunk ()
2909 "Collects the current chunk to CHUNKS and prepares for
2910 a new chunk."
2911 (when current-chunk
2912 (push (list current-chunk-pos
2913 (coerce (reverse current-chunk) 'string)) chunks)
2914 (setf current-chunk nil
2915 current-chunk-pos nil))))
2916 ;; If there's an outstanding chunk coming in collect it. Since
2917 ;; we're recursively called on skipping an input character, the
2918 ;; chunk can't possibly continue on.
2919 (when current-chunk (collect-chunk))
2920 (do ((pos initial-full-index (1+ pos)))
2921 ((= pos (length full)))
2922 (let ((cur-char (aref full pos)))
2923 (if (and (short-cur)
2924 (funcall test cur-char (short-cur)))
2925 (progn
2926 (when recurse-p
2927 ;; Try other possibilities, limiting insanely deep
2928 ;; recursion somewhat.
2929 (recursively-compute-most-completions
2930 short full test short-index (1+ pos)
2931 chunks current-chunk current-chunk-pos
2932 (not (> (length *all-chunks*)
2933 *fuzzy-recursion-soft-limit*))))
2934 (incf short-index)
2935 (add-to-chunk cur-char pos))
2936 (collect-chunk))))
2937 (collect-chunk)
2938 ;; If we've exhausted the short characters we have a match.
2939 (if (short-cur)
2940 nil
2941 (let ((rev-chunks (reverse chunks)))
2942 (push rev-chunks *all-chunks*)
2943 rev-chunks))))
2944
2945 ;;;;; Fuzzy completion scoring
2946
2947 (defparameter *fuzzy-completion-symbol-prefixes* "*+-%&?<"
2948 "Letters that are likely to be at the beginning of a symbol.
2949 Letters found after one of these prefixes will be scored as if
2950 they were at the beginning of ths symbol.")
2951 (defparameter *fuzzy-completion-symbol-suffixes* "*+->"
2952 "Letters that are likely to be at the end of a symbol.
2953 Letters found before one of these suffixes will be scored as if
2954 they were at the end of the symbol.")
2955 (defparameter *fuzzy-completion-word-separators* "-/."
2956 "Letters that separate different words in symbols. Letters
2957 after one of these symbols will be scores more highly than other
2958 letters.")
2959
2960 (defun score-completion (completion short full)
2961 "Scores the completion chunks COMPLETION as a completion from
2962 the abbreviation SHORT to the full string FULL. COMPLETION is a
2963 list like:
2964 ((0 \"mul\") (9 \"v\") (15 \"b\"))
2965 Which, if SHORT were \"mulvb\" and full were \"multiple-value-bind\",
2966 would indicate that it completed as such (completed letters
2967 capitalized):
2968 MULtiple-Value-Bind
2969
2970 Letters are given scores based on their position in the string.
2971 Letters at the beginning of a string or after a prefix letter at
2972 the beginning of a string are scored highest. Letters after a
2973 word separator such as #\- are scored next highest. Letters at
2974 the end of a string or before a suffix letter at the end of a
2975 string are scored medium, and letters anywhere else are scored
2976 low.
2977
2978 If a letter is directly after another matched letter, and its
2979 intrinsic value in that position is less than a percentage of the
2980 previous letter's value, it will use that percentage instead.
2981
2982 Finally, a small scaling factor is applied to favor shorter
2983 matches, all other things being equal."
2984 (labels ((at-beginning-p (pos)
2985 (= pos 0))
2986 (after-prefix-p (pos)
2987 (and (= pos 1)
2988 (find (aref full 0) *fuzzy-completion-symbol-prefixes*)))
2989 (word-separator-p (pos)
2990 (find (aref full pos) *fuzzy-completion-word-separators*))
2991 (after-word-separator-p (pos)
2992 (find (aref full (1- pos)) *fuzzy-completion-word-separators*))
2993 (at-end-p (pos)
2994 (= pos (1- (length full))))
2995 (before-suffix-p (pos)
2996 (and (= pos (- (length full) 2))
2997 (find (aref full (1- (length full)))
2998 *fuzzy-completion-symbol-suffixes*)))
2999 (score-or-percentage-of-previous (base-score pos chunk-pos)
3000 (if (zerop chunk-pos)
3001 base-score
3002 (max base-score
3003 (* (score-char (1- pos) (1- chunk-pos)) 0.85))))
3004 (score-char (pos chunk-pos)
3005 (score-or-percentage-of-previous
3006 (cond ((at-beginning-p pos) 10)
3007 ((after-prefix-p pos) 10)
3008 ((word-separator-p pos) 1)
3009 ((after-word-separator-p pos) 8)
3010 ((at-end-p pos) 6)
3011 ((before-suffix-p pos) 6)
3012 (t 1))
3013 pos chunk-pos))
3014 (score-chunk (chunk)
3015 (loop for chunk-pos below (length (second chunk))
3016 for pos from (first chunk)
3017 summing (score-char pos chunk-pos))))
3018 (let* ((chunk-scores (mapcar #'score-chunk completion))
3019 (length-score (/ 10.0 (1+ (- (length full) (length short))))))
3020 (values
3021 (+ (reduce #'+ chunk-scores) length-score)
3022 (list (mapcar #'list chunk-scores completion) length-score)))))
3023
3024 (defun highlight-completion (completion full)
3025 "Given a chunk definition COMPLETION and the string FULL,
3026 HIGHLIGHT-COMPLETION will create a string that demonstrates where
3027 the completion matched in the string. Matches will be
3028 capitalized, while the rest of the string will be lower-case."
3029 (let ((highlit (nstring-downcase (copy-seq full))))
3030 (dolist (chunk completion)
3031 (setf highlit (nstring-upcase highlit
3032 :start (first chunk)
3033 :end (+ (first chunk)
3034 (length (second chunk))))))
3035 highlit))
3036
3037 (defun format-fuzzy-completions (winners)
3038 "Given a list of completion objects such as on returned by
3039 FUZZY-COMPLETIONS, format the list into user-readable output."
3040 (let ((max-len
3041 (loop for winner in winners maximizing (length (first winner)))))
3042 (loop for (sym score result) in winners do
3043 (format t "~&~VA score ~8,2F ~A"
3044 max-len (highlight-completion result sym) score result))))
3045
3046
3047 ;;;; Documentation
3048
3049 (defslimefun apropos-list-for-emacs (name &optional external-only
3050 case-sensitive package)
3051 "Make an apropos search for Emacs.
3052 The result is a list of property lists."
3053 (let ((package (if package
3054 (or (find-package (string-to-package-designator package))
3055 (error "No such package: ~S" package)))))
3056 (mapcan (listify #'briefly-describe-symbol-for-emacs)
3057 (sort (remove-duplicates
3058 (apropos-symbols name external-only case-sensitive package))
3059 #'present-symbol-before-p))))
3060
3061 (defun string-to-package-designator (string)
3062 "Return a package designator made from STRING.
3063 Uses READ to case-convert STRING."
3064 (let ((*package* *swank-io-package*))
3065 (read-from-string string)))
3066
3067 (defun briefly-describe-symbol-for-emacs (symbol)
3068 "Return a property list describing SYMBOL.
3069 Like `describe-symbol-for-emacs' but with at most one line per item."
3070 (flet ((first-line (string)
3071 (let ((pos (position #\newline string)))
3072 (if (null pos) string (subseq string 0 pos)))))
3073 (let ((desc (map-if #'stringp #'first-line
3074 (describe-symbol-for-emacs symbol))))
3075 (if desc
3076 (list* :designator (to-string symbol) desc)))))
3077
3078 (defun map-if (test fn &rest lists)
3079 "Like (mapcar FN . LISTS) but only call FN on objects satisfying TEST.
3080 Example:
3081 \(map-if #'oddp #'- '(1 2 3 4 5)) => (-1 2 -3 4 -5)"
3082 (declare (type function test fn))
3083 (apply #'mapcar
3084 (lambda (x) (if (funcall test x) (funcall fn x) x))
3085 lists))
3086
3087 (defun listify (f)
3088 "Return a function like F, but which returns any non-null value
3089 wrapped in a list."
3090 (declare (type function f))
3091 (lambda (x)
3092 (let ((y (funcall f x)))
3093 (and y (list y)))))
3094
3095 (defun present-symbol-before-p (x y)
3096 "Return true if X belongs before Y in a printed summary of symbols.
3097 Sorted alphabetically by package name and then symbol name, except
3098 that symbols accessible in the current package go first."
3099 (declare (type symbol x y))
3100 (flet ((accessible (s)
3101 ;; Test breaks on NIL for package that does not inherit it
3102 (eq (find-symbol (symbol-name s) *buffer-package*) s)))
3103 (let ((ax (accessible x)) (ay (accessible y)))
3104 (cond ((and ax ay) (string< (symbol-name x) (symbol-name y)))
3105 (ax t)
3106 (ay nil)
3107 (t (let ((px (symbol-package x)) (py (symbol-package y)))
3108 (if (eq px py)
3109 (string< (symbol-name x) (symbol-name y))
3110 (string< (package-name px) (package-name py)))))))))
3111
3112 (let ((regex-hash (make-hash-table :test #'equal)))
3113 (defun compiled-regex (regex-string)
3114 (or (gethash regex-string regex-hash)
3115 (setf (gethash regex-string regex-hash)
3116 (if (zerop (length regex-string))
3117 (lambda (s) (check-type s string) t)
3118 (compile nil (slime-nregex:regex-compile regex-string)))))))
3119
3120 (defun apropos-matcher (string case-sensitive package external-only)
3121 (let* ((case-modifier (if case-sensitive #'string #'string-upcase))
3122 (regex (compiled-regex (funcall case-modifier string))))
3123 (lambda (symbol)
3124 (and (not (keywordp symbol))
3125 (if package (eq (symbol-package symbol) package) t)
3126 (if external-only (symbol-external-p symbol) t)
3127 (funcall regex (funcall case-modifier symbol))))))
3128
3129 (defun apropos-symbols (string external-only case-sensitive package)
3130 (let ((result '())
3131 (matchp (apropos-matcher string case-sensitive package external-only)))
3132 (with-package-iterator (next (or package (list-all-packages))
3133 :external :internal)
3134 (loop
3135 (multiple-value-bind (morep symbol) (next)
3136 (cond ((not morep)
3137 (return))
3138 ((funcall matchp symbol)
3139 (push symbol result))))))
3140 result))
3141
3142 (defun call-with-describe-settings (fn)
3143 (let ((*print-readably* nil))
3144 (funcall fn)))
3145
3146 (defmacro with-describe-settings ((&rest _) &body body)
3147 (declare (ignore _))
3148 `(call-with-describe-settings (lambda () ,@body)))
3149
3150 (defun describe-to-string (object)
3151 (with-describe-settings ()
3152 (with-output-to-string (*standard-output*)
3153 (describe object))))
3154
3155 (defslimefun describe-symbol (symbol-name)
3156 (with-buffer-syntax ()
3157 (describe-to-string (parse-symbol-or-lose symbol-name))))
3158
3159 (defslimefun describe-function (name)
3160 (with-buffer-syntax ()
3161 (let ((symbol (parse-symbol-or-lose name)))
3162 (describe-to-string (or (macro-function symbol)
3163 (symbol-function symbol))))))
3164
3165 (defslimefun describe-definition-for-emacs (name kind)
3166 (with-buffer-syntax ()
3167 (with-describe-settings ()
3168 (with-output-to-string (*standard-output*)
3169 (describe-definition (parse-symbol-or-lose name) kind)))))
3170
3171 (defslimefun documentation-symbol (symbol-name &optional default)
3172 (with-buffer-syntax ()
3173 (multiple-value-bind (sym foundp) (parse-symbol symbol-name)
3174 (if foundp
3175 (let ((vdoc (documentation sym 'variable))
3176 (fdoc (documentation sym 'function)))
3177 (or (and (or vdoc fdoc)
3178 (concatenate 'string
3179 fdoc
3180 (and vdoc fdoc '(#\Newline #\Newline))
3181 vdoc))
3182 default))
3183 default))))
3184
3185
3186 ;;;; Package Commands
3187
3188 (defslimefun list-all-package-names (&optional include-nicknames)
3189 "Return a list of all package names.
3190 Include the nicknames if INCLUDE-NICKNAMES is true."
3191 (loop for package in (list-all-packages)
3192 collect (package-name package)
3193 when include-nicknames append (package-nicknames package)))
3194
3195
3196 ;;;; Tracing
3197
3198 ;; Use eval for the sake of portability...
3199 (defun tracedp (fspec)
3200 (member fspec (eval '(trace))))
3201
3202 (defslimefun swank-toggle-trace (spec-string)
3203 (let ((spec (from-string spec-string)))
3204 (cond ((consp spec) ; handle complicated cases in the backend
3205 (toggle-trace spec))
3206 ((tracedp spec)
3207 (eval `(untrace ,spec))
3208 (format nil "~S is now untraced." spec))
3209 (t
3210 (eval `(trace ,spec))
3211 (format nil "~S is now traced." spec)))))
3212
3213 (defslimefun untrace-all ()
3214 (untrace))
3215
3216
3217 ;;;; Undefing
3218
3219 (defslimefun undefine-function (fname-string)
3220 (let ((fname (from-string fname-string)))
3221 (format nil "~S" (fmakunbound fname))))
3222
3223
3224 ;;;; Profiling
3225
3226 (defun profiledp (fspec)
3227 (member fspec (profiled-functions)))
3228
3229 (defslimefun toggle-profile-fdefinition (fname-string)
3230 (let ((fname (from-string fname-string)))
3231 (cond ((profiledp fname)
3232 (unprofile fname)
3233 (format nil "~S is now unprofiled." fname))
3234 (t
3235 (profile fname)
3236 (format nil "~S is now profiled." fname)))))
3237
3238
3239 ;;;; Source Locations
3240
3241 (defslimefun find-definitions-for-emacs (name)
3242 "Return a list ((DSPEC LOCATION) ...) of definitions for NAME.
3243 DSPEC is a string and LOCATION a source location. NAME is a string."
3244 (multiple-value-bind (sexp error)
3245 (ignore-errors (values (from-string name)))
3246 (cond (error '())
3247 (t (loop for (dspec loc) in (find-definitions sexp)
3248 collect (list (to-string dspec) loc))))))
3249
3250 (defun alistify (list key test)
3251 "Partition the elements of LIST into an alist. KEY extracts the key
3252 from an element and TEST is used to compare keys."
3253 (declare (type function key))
3254 (let ((alist '()))
3255 (dolist (e list)
3256 (let* ((k (funcall key e))
3257 (probe (assoc k alist :test test)))
3258 (if probe
3259 (push e (cdr probe))
3260 (push (cons k (list e)) alist))))
3261 alist))
3262
3263 (defun location-position< (pos1 pos2)
3264 (cond ((and (position-p pos1) (position-p pos2))
3265 (< (position-pos pos1)
3266 (position-pos pos2)))
3267 (t nil)))
3268
3269 (defun partition (list test key)
3270 (declare (type function test key))
3271 (loop for e in list
3272 if (funcall test (funcall key e)) collect e into yes
3273 else collect e into no
3274 finally (return (values yes no))))
3275
3276 (defstruct (xref (:conc-name xref.)
3277 (:type list))
3278 dspec location)
3279
3280 (defun location-valid-p (location)
3281 (eq (car location) :location))
3282
3283 (defun xref-buffer (xref)
3284 (location-buffer (xref.location xref)))
3285
3286 (defun xref-position (xref)
3287 (location-buffer (xref.location xref)))
3288
3289 (defun group-xrefs (xrefs)
3290 "Group XREFS, a list of the form ((DSPEC LOCATION) ...) by location.
3291 The result is a list of the form ((LOCATION . ((DSPEC . LOCATION) ...)) ...)."
3292 (multiple-value-bind (resolved errors)
3293 (partition xrefs #'location-valid-p #'xref.location)
3294 (let ((alist (alistify resolved #'xref-buffer #'equal)))
3295 (append
3296 (loop for (buffer . list) in alist
3297 collect (cons (second buffer)
3298 (mapcar (lambda (xref)
3299 (cons (to-string (xref.dspec xref))
3300 (xref.location xref)))
3301 (sort list #'location-position<
3302 :key #'xref-position))))
3303 (if errors
3304 (list (cons "Unresolved"
3305 (mapcar (lambda (xref)
3306 (cons (to-string (xref.dspec xref))
3307 (xref.location xref)))
3308 errors))))))))
3309
3310 (defslimefun xref (type symbol-name)
3311 (let ((symbol (parse-symbol-or-lose symbol-name *buffer-package*)))
3312 (group-xrefs
3313 (ecase type
3314 (:calls (who-calls symbol))
3315 (:calls-who (calls-who symbol))
3316 (:references (who-references symbol))
3317 (:binds (who-binds symbol))
3318 (:sets (who-sets symbol))
3319 (:macroexpands (who-macroexpands symbol))
3320 (:specializes (who-specializes symbol))
3321 (:callers (list-callers symbol))
3322 (:callees (list-callees symbol))))))
3323
3324
3325 ;;;; Inspecting
3326
3327 (defun common-seperated-spec (list &optional (callback (lambda (v)
3328 `(:value ,v))))
3329 (butlast
3330 (loop
3331 for i in list
3332 collect (funcall callback i)
3333 collect ", ")))
3334
3335 (defun inspector-princ (list)
3336 "Like princ-to-string, but don't rewrite (function foo) as #'foo.
3337 Do NOT pass circular lists to this function."
3338 (let ((*print-pprint-dispatch* (copy-pprint-dispatch)))
3339 (set-pprint-dispatch '(cons (member function)) nil)
3340 (princ-to-string list)))
3341
3342 (defmethod inspect-for-emacs ((object cons) inspector)
3343 (declare (ignore inspector))
3344 (if (consp (cdr object))
3345 (inspect-for-emacs-list object)
3346 (inspect-for-emacs-simple-cons object)))
3347
3348 (defun inspect-for-emacs-simple-cons (cons)
3349 (values "A cons cell."
3350 (label-value-line*
3351 ('car (car cons))
3352 ('cdr (cdr cons)))))
3353
3354 (defun inspect-for-emacs-list (list)
3355 (let ((maxlen 40))
3356 (multiple-value-bind (length tail) (safe-length list)
3357 (flet ((frob (title list)
3358 (let ((lines
3359 (do ((i 0 (1+ i))
3360 (l list (cdr l))
3361 (a '() (cons (label-value-line i (car l)) a)))
3362 ((not (consp l))
3363 (let ((a (if (null l)
3364 a
3365 (cons (label-value-line :tail l) a))))
3366 (reduce #'append (reverse a) :from-end t))))))
3367 (values title (append '("Elements:" (:newline)) lines)))))
3368
3369 (cond ((not length) ; circular
3370 (frob "A circular list."
3371 (cons (car list)
3372 (ldiff (cdr list) list))))
3373 ((and (<= length maxlen) (not tail))
3374 (frob "A proper list." list))
3375 (tail
3376 (frob "An improper list." list))
3377 (t
3378 (frob "A proper list." list)))))))
3379
3380 ;; (inspect-for-emacs-list '#1=(a #1# . #1# ))
3381
3382 (defun safe-length (list)
3383 "Similar to `list-length', but avoid errors on improper lists.
3384 Return two values: the length of the list and the last cdr.
3385 NIL is returned if the list is circular."
3386 (do ((n 0 (+ n 2)) ;Counter.
3387 (fast list (cddr fast)) ;Fast pointer: leaps by 2.
3388 (slow list (cdr slow))) ;Slow pointer: leaps by 1.
3389 (nil)
3390 (cond ((null fast) (return (values n nil)))
3391 ((not (consp fast)) (return (values n fast)))
3392 ((null (cdr fast)) (return (values (1+ n) (cdr fast))))
3393 ((and (eq fast slow) (> n 0)) (return nil))
3394 ((not (consp (cdr fast))) (return (values (1+ n) (cdr fast)))))))
3395
3396 (defvar *slime-inspect-contents-limit* nil "How many elements of
3397 a hash table or array to show by default. If table has more than
3398 this then offer actions to view more. Set to nil for no limit." )
3399
3400 (defmethod inspect-for-emacs ((ht hash-table) inspector)
3401 (declare (ignore inspector))
3402 (values (prin1-to-string ht)
3403 (append
3404 (label-value-line*
3405 ("Count" (hash-table-count ht))
3406 ("Size" (hash-table-size ht))
3407 ("Test" (hash-table-test ht))
3408 ("Rehash size" (hash-table-rehash-size ht))
3409 ("Rehash threshold" (hash-table-rehash-threshold ht)))
3410 '("Contents: " (:newline))
3411 (if (and *slime-inspect-contents-limit*
3412 (>= (hash-table-count ht) *slime-inspect-contents-limit*))
3413 (inspect-bigger-piece-actions ht (hash-table-count ht))
3414 nil)
3415 (loop for key being the hash-keys of ht
3416 for value being the hash-values of ht
3417 repeat (or *slime-inspect-contents-limit* most-positive-fixnum)
3418 append `((:value ,key) " = " (:value ,value) (:newline))
3419 )
3420
3421 )))
3422
3423 (defmethod inspect-bigger-piece-actions (thing size)
3424 (append
3425 (if (> size *slime-inspect-contents-limit*)
3426 (list (inspect-show-more-action thing)
3427 '(:newline))
3428 nil)
3429 (list (inspect-whole-thing-action thing size)
3430 '(:newline))))
3431
3432 (defmethod inspect-whole-thing-action (thing size)
3433 `(:action ,(format nil "Inspect all ~a elements."
3434 size)
3435 ,(lambda()
3436 (let ((*slime-inspect-contents-limit* nil))
3437 (values
3438 (swank::inspect-object thing)
3439 :replace)
3440 ))))
3441
3442 (defmethod inspect-show-more-action (thing)
3443 `(:action ,(format nil "~a elements shown. Prompt for how many to inspect..."
3444 *slime-inspect-contents-limit* )
3445 ,(lambda()
3446 (let ((*slime-inspect-contents-limit*
3447 (progn (format t "How many elements should be shown? ") (read))))
3448 (values
3449 (swank::inspect-object thing)
3450 :replace)
3451 ))
3452 ))
3453
3454 (defmethod inspect-for-emacs ((array array) inspector)
3455 (declare (ignore inspector))
3456 (values "An array."
3457 (append
3458 (label-value-line*
3459 ("Dimensions" (array-dimensions array))
3460 ("Its element type is" (array-element-type array))
3461 ("Total size" (array-total-size array))
3462 ("Adjustable" (adjustable-array-p array)))
3463 (when (array-has-fill-pointer-p array)
3464 (label-value-line "Fill pointer" (fill-pointer array)))
3465 '("Contents:" (:newline))
3466 (if (and *slime-inspect-contents-limit*
3467 (>= (array-total-size array) *slime-inspect-contents-limit*))
3468 (inspect-bigger-piece-actions array (length array))
3469 nil)
3470 (loop for i below (or *slime-inspect-contents-limit* (array-total-size array))
3471 append (label-value-line i (row-major-aref array i))))))
3472
3473 (defmethod inspect-for-emacs ((char character) inspector)
3474 (declare (ignore inspector))
3475 (values "A character."
3476 (append
3477 (label-value-line*
3478 ("Char code" (char-code char))
3479 ("Lower cased" (char-downcase char))
3480 ("Upper cased" (char-upcase char)))
3481 (if (get-macro-character char)
3482 `("In the current readtable ("
3483 (:value ,*readtable*) ") it is a macro character: "
3484 (:value ,(get-macro-character char)))))))
3485
3486 (defun docstring-ispec (label object kind)
3487 "Return a inspector spec if OBJECT has a docstring of of kind KIND."
3488 (let ((docstring (documentation object kind)))
3489 (cond ((not docstring) nil)
3490 ((< (+ (length label) (length docstring))
3491 75)
3492 (list label ": " docstring '(:newline)))
3493 (t
3494 (list label ": " '(:newline) " " docstring '(:newline))))))
3495
3496 (defmethod inspect-for-emacs ((symbol symbol) inspector)
3497 (declare (ignore inspector))
3498 (let ((package (symbol-package symbol)))
3499 (multiple-value-bind (_symbol status)
3500 (and package (find-symbol (string symbol) package))
3501 (declare (ignore _symbol))
3502 (values
3503 "A symbol."
3504 (append
3505 (label-value-line "Its name is" (symbol-name symbol))
3506 ;;
3507 ;; Value
3508 (cond ((boundp symbol)
3509 (label-value-line (if (constantp symbol)
3510 "It is a constant of value"
3511 "It is a global variable bound to")
3512 (symbol-value symbol)))
3513 (t '("It is unbound." (:newline))))
3514 (docstring-ispec "Documentation" symbol 'variable)
3515 (multiple-value-bind (expansion definedp) (macroexpand symbol)
3516 (if definedp
3517 (label-value-line "It is a symbol macro with expansion"
3518 expansion)))
3519 ;;
3520 ;; Function
3521 (if (fboundp symbol)
3522 (append (if (macro-function symbol)
3523 `("It a macro with macro-function: "
3524 (:value ,(macro-function symbol)))
3525 `("It is a function: "
3526 (:value ,(symbol-function symbol))))
3527 `(" " (:action "[make funbound]"
3528 ,(lambda () (fmakunbound symbol))))
3529 `((:newline)))
3530 `("It has no function value." (:newline)))
3531 (docstring-ispec "Function Documentation" symbol 'function)
3532 (if (compiler-macro-function symbol)
3533 (label-value-line "It also names the compiler macro"
3534 (compiler-macro-function symbol)))
3535 (docstring-ispec "Compiler Macro Documentation"
3536 symbol 'compiler-macro)
3537 ;;
3538 ;; Package
3539 (if package
3540 `("It is " ,(string-downcase (string status))
3541 " to the package: "
3542 (:value ,package ,(package-name package))
3543 ,@(if (eq :internal status)
3544 `(" "
3545 (:action "[export it]"
3546 ,(lambda () (export symbol package)))))
3547 " "
3548 (:action "[unintern it]"
3549 ,(lambda () (unintern symbol package)))
3550 (:newline))
3551 '("It is a non-interned symbol." (:newline)))
3552 ;;
3553 ;; Plist
3554 (label-value-line "Property list" (symbol-plist symbol))
3555 ;;
3556 ;; Class
3557 (if (find-class symbol nil)
3558 `("It names the class "
3559 (:value ,(find-class symbol) ,(string symbol))
3560 " "
3561 (:action "[remove]"
3562 ,(lambda () (setf (find-class symbol) nil)))
3563 (:newline)))
3564 ;;
3565 ;; More package
3566 (if (find-package symbol)
3567 (label-value-line "It names the package" (find-package symbol)))
3568 )))))
3569
3570 (defmethod inspect-for-emacs ((f function) inspector)
3571 (declare (ignore inspector))
3572 (values "A function."
3573 (append
3574 (label-value-line "Name" (function-name f))
3575 `("Its argument list is: "
3576 ,(inspector-princ (arglist f)) (:newline))
3577 (docstring-ispec "Documentation" f t)
3578 (if (function-lambda-expression f)
3579 (label-value-line "Lambda Expression"
3580 (function-lambda-expression f))))))
3581
3582 (defun method-specializers-for-inspect (method)
3583 "Return a \"pretty\" list of the method's specializers. Normal
3584 specializers are replaced by the name of the class, eql
3585 specializers are replaced by `(eql ,object)."
3586 (mapcar (lambda (spec)
3587 (typecase spec
3588 (swank-mop:eql-specializer
3589 `(eql ,(swank-mop:eql-specializer-object spec)))
3590 (t (swank-mop:class-name spec))))
3591 (swank-mop:method-specializers method)))
3592
3593 (defun method-for-inspect-value (method)
3594 "Returns a \"pretty\" list describing METHOD. The first element
3595 of the list is the name of generic-function method is
3596 specialiazed on, the second element is the method qualifiers,
3597 the rest of the list is the method's specialiazers (as per
3598 method-specializers-for-inspect)."
3599 (append (list (swank-mop:generic-function-name
3600 (swank-mop:method-generic-function method)))
3601 (swank-mop:method-qualifiers method)
3602 (method-specializers-for-inspect method)))
3603
3604 (defmethod inspect-for-emacs ((o standard-object) inspector)
3605 (declare (ignore inspector))
3606 (values "An object."
3607 `("Class: " (:value ,(class-of o)) (:newline)
3608 "Slots:" (:newline)
3609 ,@(loop
3610 for slot in (swank-mop:class-slots (class-of o))
3611 for slot-def = (find-effective-slot o slot)
3612 for slot-name = (swank-mop:slot-definition-name slot-def)
3613 collect `(:value ,slot-def ,(string slot-name))
3614 collect " = "
3615 collect (if (slot-boundp o slot-name)
3616 `(:value ,(slot-value o slot-name))
3617 "#<unbound>")
3618 collect '(:newline)))))
3619
3620 (defun find-effective-slot (o slot)
3621 ;; find the direct slot with the same name as SLOT (an effective
3622 ;; slot).
3623 (or (find-if (lambda (a)
3624 (eql (swank-mop:slot-definition-name a)
3625 (swank-mop:slot-definition-name slot)))
3626 (swank-mop:class-direct-slots (class-of o)))
3627 slot))
3628
3629 (defvar *gf-method-getter* 'methods-by-applicability
3630 "This function is called to get the methods of a generic function.
3631 The default returns the method sorted by applicability.
3632 See `methods-by-applicability'.")
3633
3634 (defun specializer< (specializer1 specializer2)
3635 "Return true if SPECIALIZER1 is more specific than SPECIALIZER2."
3636 (let ((s1 specializer1) (s2 specializer2) )
3637 (cond ((typep s1 'swank-mop:eql-specializer)
3638 (not (typep s2 'swank-mop:eql-specializer)))
3639 (t
3640 (flet ((cpl (class)
3641 (and (swank-mop:class-finalized-p class)
3642 (swank-mop:class-precedence-list class))))
3643 (member s2 (cpl s1)))))))
3644
3645 (defun methods-by-applicability (gf)
3646 "Return methods ordered by most specific argument types.
3647
3648 `method-specializer<' is used for sorting."
3649 ;; FIXME: argument-precedence-order and qualifiers are ignored.
3650 (let ((methods (copy-list (swank-mop:generic-function-methods gf))))
3651 (labels ((method< (meth1 meth2)
3652 (loop for s1 in (swank-mop:method-specializers meth1)
3653 for s2 in (swank-mop:method-specializers meth2)
3654 do (cond ((specializer< s2 s1) (return nil))
3655 ((specializer< s1 s2) (return t))))))
3656 (stable-sort methods #'method<))))
3657
3658 (defun abbrev-doc (doc &optional (maxlen 80))
3659 "Return the first sentence of DOC, but not more than MAXLAN characters."
3660 (subseq doc 0 (min (1+ (or (position #\. doc) (1- maxlen)))
3661 maxlen
3662 (length doc))))
3663
3664 (defun all-slots-for-inspector (object)
3665 (append (list "------------------------------" '(:newline)
3666 "All Slots:" '(:newline))
3667 (loop
3668 with direct-slots = (swank-mop:class-direct-slots (class-of object))
3669 for slot in (swank-mop:class-slots (class-of object))
3670 for slot-def = (or (find-if (lambda (a)
3671 ;; find the direct slot
3672 ;; with the same name
3673 ;; as SLOT (an
3674 ;; effective slot).
3675 (eql (swank-mop:slot-definition-name a)
3676 (swank-mop:slot-definition-name slot)))
3677 direct-slots)
3678 slot)
3679 collect `(:value ,slot-def ,(inspector-princ (swank-mop:slot-definition-name slot-def)))
3680 collect " = "
3681 if (slot-boundp object (swank-mop:slot-definition-name slot-def))
3682 collect `(:value ,(slot-value object (swank-mop:slot-definition-name slot-def)))
3683 else
3684 collect "#<unbound>"
3685 collect '(:newline))))
3686
3687 (defmethod inspect-for-emacs ((gf standard-generic-function) inspector)
3688 (declare (ignore inspector))
3689 (flet ((lv (label value) (label-value-line label value)))
3690 (values
3691 "A generic function."
3692 (append
3693 (lv "Name" (swank-mop:generic-function-name gf))
3694 (lv "Arguments" (swank-mop:generic-function-lambda-list gf))
3695 (docstring-ispec "Documentation" gf t)
3696 (lv "Method class" (swank-mop:generic-function-method-class gf))
3697 (lv "Method combination"
3698 (swank-mop:generic-function-method-combination gf))
3699 `("Methods: " (:newline))
3700 (loop for method in (funcall *gf-method-getter* gf) append
3701 `((:value ,method ,(inspector-princ
3702 ;; drop the name of the GF
3703 (cdr (method-for-inspect-value method))))
3704 " "
3705 (:action "[remove method]"
3706 ,(let ((m method)) ; LOOP reassigns method
3707 (lambda ()
3708 (remove-method gf m))))
3709 (:newline)))
3710 `((:newline))
3711 (all-slots-for-inspector gf)))))
3712
3713 (defmethod inspect-for-emacs ((method standard-method) inspector)
3714 (declare (ignore inspector))
3715 (values "A method."
3716 `("Method defined on the generic function "
3717 (:value ,(swank-mop:method-generic-function method)
3718 ,(inspector-princ
3719 (swank-mop:generic-function-name
3720 (swank-mop:method-generic-function method))))
3721 (:newline)
3722 ,@(docstring-ispec "Documentation" method t)
3723 "Lambda List: " (:value ,(swank-mop:method-lambda-list method))
3724 (:newline)
3725 "Specializers: " (:value ,(swank-mop:method-specializers method)
3726 ,(inspector-princ (method-specializers-for-inspect method)))
3727 (:newline)
3728 "Qualifiers: " (:value ,(swank-mop:method-qualifiers method))
3729 (:newline)
3730 "Method function: " (:value ,(swank-mop:method-function method))
3731 (:newline)
3732 ,@(all-slots-for-inspector method))))
3733
3734 (defmethod inspect-for-emacs ((class standard-class) inspector)
3735 (declare (ignore inspector))
3736 (values "A class."
3737 `("Name: " (:value ,(class-name class))
3738 (:newline)
3739 "Super classes: "
3740 ,@(common-seperated-spec (swank-mop:class-direct-superclasses class))
3741 (:newline)
3742 "Direct Slots: "
3743 ,@(common-seperated-spec
3744 (swank-mop:class-direct-slots class)
3745 (lambda (slot)
3746 `(:value ,slot ,(inspector-princ (swank-mop:slot-definition-name slot)))))
3747 (:newline)
3748 "Effective Slots: "
3749 ,@(if (swank-mop:class-finalized-p class)
3750 (common-seperated-spec
3751 (swank-mop:class-slots class)
3752 (lambda (slot)
3753 `(:value ,slot ,(inspector-princ
3754 (swank-mop:slot-definition-name slot)))))
3755 '("#<N/A (class not finalized)>"))
3756 (:newline)
3757 ,@(when (documentation class t)
3758 `("Documentation:" (:newline) ,(documentation class t) (:newline)))
3759 "Sub classes: "
3760 ,@(common-seperated-spec (swank-mop:class-direct-subclasses class)
3761 (lambda (sub)
3762 `(:value ,sub ,(inspector-princ (class-name sub)))))
3763 (:newline)
3764 "Precedence List: "
3765 ,@(if (swank-mop:class-finalized-p class)
3766 (common-seperated-spec (swank-mop:class-precedence-list class)
3767 (lambda (class)
3768 `(:value ,class ,(inspector-princ (class-name class)))))
3769 '("#<N/A (class not finalized)>"))
3770 (:newline)
3771 ,@(when (swank-mop:specializer-direct-methods class)
3772 `("It is used as a direct specializer in the following methods:" (:newline)
3773 ,@(loop
3774 for method in (sort (copy-list (swank-mop:specializer-direct-methods class))
3775 #'string< :key (lambda (x)
3776 (symbol-name
3777 (let ((name (swank-mop::generic-function-name
3778 (swank-mop::method-generic-function x))))
3779 (if (symbolp name) name (second name))))))
3780 collect " "
3781 collect `(:value ,method ,(inspector-princ (method-for-inspect-value method)))
3782 collect '(:newline)
3783 if (documentation method t)
3784 collect " Documentation: " and
3785 collect (abbrev-doc (documentation method t)) and
3786 collect '(:newline))))
3787 "Prototype: " ,(if (swank-mop:class-finalized-p class)
3788 `(:value ,(swank-mop:class-prototype class))
3789 '"#<N/A (class not finalized)>")
3790 (:newline)
3791 ,@(all-slots-for-inspector class))))
3792
3793 (defmethod inspect-for-emacs ((slot swank-mop:standard-slot-definition) inspector)
3794 (declare (ignore inspector))
3795 (values "A slot."
3796 `("Name: " (:value ,(swank-mop:slot-definition-name slot))
3797 (:newline)
3798 ,@(when (swank-mop:slot-definition-documentation slot)
3799 `("Documentation:" (:newline)
3800 (:value ,(swank-mop:slot-definition-documentation slot))
3801 (:newline)))
3802 "Init args: " (:value ,(swank-mop:slot-definition-initargs slot)) (:newline)
3803 "Init form: " ,(if (swank-mop:slot-definition-initfunction slot)
3804 `(:value ,(swank-mop:slot-definition-initform slot))
3805 "#<unspecified>") (:newline)
3806 "Init function: " (:value ,(swank-mop:slot-definition-initfunction slot))
3807 (:newline)
3808 ,@(all-slots-for-inspector slot))))
3809
3810 (defmethod inspect-for-emacs ((package package) inspector)
3811 (declare (ignore inspector))
3812 (let ((internal-symbols '())
3813 (external-symbols '()))
3814 (do-symbols (sym package)
3815 (when (eq package (symbol-package sym))
3816 (push sym internal-symbols)
3817 (multiple-value-bind (symbol status)
3818 (find-symbol (symbol-name sym) package)
3819 (declare (ignore symbol))
3820 (when (eql :external status)
3821 (push sym external-symbols)))))
3822 (setf internal-symbols (sort internal-symbols #'string-lessp)
3823 external-symbols (sort external-symbols #'string-lessp))
3824 (values "A package."
3825 `("Name: " (:value ,(package-name package))
3826 (:newline)
3827 "Nick names: " ,@(common-seperated-spec (sort (package-nicknames package) #'string-lessp))
3828 (:newline)
3829 ,@(when (documentation package t)
3830 `("Documentation:" (:newline)
3831 ,(documentation package t) (:newline)))
3832 "Use list: " ,@(common-seperated-spec (sort (package-use-list package) #'string-lessp :key #'package-name)
3833 (lambda (pack)
3834 `(:value ,pack ,(inspector-princ (package-name pack)))))
3835 (:newline)
3836 "Used by list: " ,@(common-seperated-spec (sort (package-used-by-list package) #'string-lessp :key #'package-name)
3837 (lambda (pack)
3838 `(:value ,pack ,(inspector-princ (package-name pack)))))
3839 (:newline)
3840 ,(if (null external-symbols)
3841 "0 external symbols."
3842 `(:value ,external-symbols ,(format nil "~D external symbol~:P." (length external-symbols))))
3843 (:newline)
3844 ,(if (null internal-symbols)
3845 "0 internal symbols."
3846 `(:value ,internal-symbols ,(format nil "~D internal symbol~:P." (length internal-symbols))))
3847 (:newline)
3848 ,(if (null (package-shadowing-symbols package))
3849 "0 shadowed symbols."
3850 `(:value ,(package-shadowing-symbols package)
3851 ,(format nil "~D shadowed symbol~:P." (length (package-shadowing-symbols package)))))))))
3852
3853 (defmethod inspect-for-emacs ((pathname pathname) inspector)
3854 (declare (ignore inspector))
3855 (values (if (wild-pathname-p pathname)
3856 "A wild pathname."
3857 "A pathname.")
3858 (append (label-value-line*
3859 ("Namestring" (namestring pathname))
3860 ("Host" (pathname-host pathname))
3861 ("Device" (pathname-device pathname))
3862 ("Directory" (pathname-directory pathname))
3863 ("Name" (pathname-name pathname))
3864 ("Type" (pathname-type pathname))
3865 ("Version" (pathname-version pathname)))
3866 (unless (or (wild-pathname-p pathname)
3867 (not (probe-file pathname)))
3868 (label-value-line "Truename" (truename pathname))))))
3869
3870 (defmethod inspect-for-emacs ((pathname logical-pathname) inspector)
3871 (declare (ignore inspector))
3872 (values "A logical pathname."
3873 (append
3874 (label-value-line*
3875 ("Namestring" (namestring pathname))
3876 ("Physical pathname: " (translate-logical-pathname pathname)))
3877 `("Host: " (pathname-host pathname)
3878 " (" (:value ,(logical-pathname-translations
3879 (pathname-host pathname)))
3880 "other translations)"
3881 (:newline))
3882 (label-value-line*
3883 ("Directory" (pathname-directory pathname))
3884 ("Name" (pathname-name pathname))
3885 ("Type" (pathname-type pathname))
3886 ("Version" (pathname-version pathname))
3887 ("Truename" (if (not (wild-pathname-p pathname))
3888 (probe-file pathname)))))))
3889
3890 (defmethod inspect-for-emacs ((n number) inspector)
3891 (declare (ignore inspector))
3892 (values "A number." `("Value: " ,(princ-to-string n))))
3893
3894 (defun format-iso8601-time (time-value &optional include-timezone-p)
3895 "Formats a universal time TIME-VALUE in ISO 8601 format, with
3896 the time zone included if INCLUDE-TIMEZONE-P is non-NIL"
3897 ;; Taken from http://www.pvv.ntnu.no/~nsaa/ISO8601.html
3898 ;; Thanks, Nikolai Sandved and Thomas Russ!
3899 (flet ((format-iso8601-timezone (zone)
3900 (if (zerop zone)
3901 "Z"
3902 (multiple-value-bind (h m) (truncate (abs zone) 1.0)
3903 ;; Tricky. Sign of time zone is reversed in ISO 8601
3904 ;; relative to Common Lisp convention!
3905 (format nil "~:[+~;-~]~2,'0D:~2,'0D"
3906 (> zone 0) h (round m))))))
3907 (multiple-value-bind (second minute hour day month year dow dst zone)
3908 (decode-universal-time time-value)
3909 (declare (ignore dow dst))
3910 (format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0D~:[~*~;~A~]"
3911 year month day hour minute second
3912 include-timezone-p (format-iso8601-timezone zone)))))
3913
3914 (defmethod inspect-for-emacs ((i integer) inspector)
3915 (declare (ignore inspector))
3916 (values "A number."
3917 (append
3918 `(,(format nil "Value: ~D = #x~X = #o~O = #b~,,' ,8:B = ~E"
3919 i i i i i)
3920 (:newline))
3921 (if (< -1 i char-code-limit)
3922 (label-value-line "Corresponding character" (code-char i)))
3923 (label-value-line "Length" (integer-length i))
3924 (ignore-errors
3925 (list "As time: "
3926 (format-iso8601-time i t))))))
3927
3928 (defmethod inspect-for-emacs ((c complex) inspector)
3929 (declare (ignore inspector))
3930 (values "A complex number."
3931 (label-value-line*
3932 ("Real part" (realpart c))
3933 ("Imaginary part" (imagpart c)))))
3934
3935 (defmethod inspect-for-emacs ((r ratio) inspector)
3936 (declare (ignore inspector))
3937 (values "A non-integer ratio."
3938 (label-value-line*
3939 ("Numerator" (numerator r))
3940 ("Denominator" (denominator r))
3941 ("As float" (float r)))))
3942
3943 (defmethod inspect-for-emacs ((f float) inspector)
3944 (declare (ignore inspector))
3945 (multiple-value-bind (significand exponent sign) (decode-float f)
3946 (values "A floating point number."
3947 (append
3948 `("Scientific: " ,(format nil "~E" f) (:newline)
3949 "Decoded: "
3950 (:value ,sign) " * "
3951 (:value ,significand) " * "
3952 (:value ,(float-radix f)) "^" (:value ,exponent) (:newline))
3953 (label-value-line "Digits" (float-digits f))
3954 (label-value-line "Precision" (float-precision f))))))
3955
3956 (defvar *inspectee*)
3957 (defvar *inspectee-parts*)
3958 (defvar *inspectee-actions*)
3959 (defvar *inspector-stack* '())
3960 (defvar *inspector-history* (make-array 10 :adjustable t :fill-pointer 0))
3961 (declaim (type vector *inspector-history*))
3962 (defvar *inspect-length* 30)
3963
3964 (defun reset-inspector ()
3965 (setq *inspectee* nil
3966 *inspector-stack* nil
3967 *inspectee-parts* (make-array 10 :adjustable t :fill-pointer 0)
3968 *inspectee-actions* (make-array 10 :adjustable t :fill-pointer 0)
3969 *inspector-history* (make-array 10 :adjustable t :fill-pointer 0)))
3970
3971 (defslimefun init-inspector (string)
3972 (with-buffer-syntax ()
3973 (reset-inspector)
3974 (inspect-object (eval (read-from-string string)))))
3975
3976 (defun print-part-to-string (value)
3977 (let ((string (to-string value))
3978 (pos (position value *inspector-history*)))
3979 (if pos
3980 (format nil "#~D=~A" pos string)
3981 string)))
3982
3983 (defun inspector-content-for-emacs (specs)
3984 (loop for part in specs collect
3985 (etypecase part
3986 (null ; XXX encourages sloppy programming
3987 nil)
3988 (string part)
3989 (cons (destructure-case part
3990 ((:newline)
3991 (string #\newline))
3992 ((:value obj &optional str)
3993 (value-part-for-emacs obj str))
3994 ((:action label lambda)
3995 (action-part-for-emacs label lambda)))))))
3996
3997 (defun assign-index (object vector)
3998 (let ((index (fill-pointer vector)))
3999 (vector-push-extend object vector)
4000 index))
4001
4002 (defun value-part-for-emacs (object string)
4003 (list :value
4004 (or string (print-part-to-string object))
4005 (assign-index object *inspectee-parts*)))
4006
4007 (defun action-part-for-emacs (label lambda)
4008 (list :action label (assign-index lambda *inspectee-actions*)))
4009
4010 (defun inspect-object (object &optional (inspector (make-default-inspector)))
4011 (push (setq *inspectee* object) *inspector-stack*)
4012 (unless (find object *inspector-history*)
4013 (vector-push-extend object *inspector-history*))
4014 (let ((*print-pretty* nil) ; print everything in the same line
4015 (*print-circle* t)
4016 (*print-readably* nil))
4017 (multiple-value-bind (title content)
4018 (inspect-for-emacs object inspector)
4019 (list :title title
4020 :type (to-string (type-of object))
4021 :content (inspector-content-for-emacs content)))))
4022
4023 (defslimefun inspector-nth-part (index)
4024 (aref *inspectee-parts* index))
4025
4026 (defslimefun inspect-nth-part (index)
4027 (with-buffer-syntax ()
4028 (inspect-object (inspector-nth-part index))))
4029
4030 (defslimefun inspector-call-nth-action (index &rest args)
4031 (multiple-value-bind (value replace) (apply (aref *inspectee-actions* index) args)
4032 (if (eq replace :replace)
4033 value
4034 (inspect-object (pop *inspector-stack*)))))
4035
4036 (defslimefun inspector-pop ()
4037 "Drop the inspector stack and inspect the second element. Return
4038 nil if there's no second element."
4039 (with-buffer-syntax ()
4040 (cond ((cdr *inspector-stack*)
4041 (pop *inspector-stack*)
4042 (inspect-object (pop *inspector-stack*)))
4043 (t nil))))
4044
4045 (defslimefun inspector-next ()
4046 "Inspect the next element in the *inspector-history*."
4047 (with-buffer-syntax ()
4048 (let ((position (position *inspectee* *inspector-history*)))
4049 (cond ((= (1+ position) (length *inspector-history*))
4050 nil)
4051 (t (inspect-object (aref *inspector-history* (1+ position))))))))
4052
4053 (defslimefun inspector-reinspect ()
4054 (inspect-object *inspectee*))
4055
4056 (defslimefun quit-inspector ()
4057 (reset-inspector)
4058 nil)
4059
4060 (defslimefun describe-inspectee ()
4061 "Describe the currently inspected object."
4062 (with-buffer-syntax ()
4063 (describe-to-string *inspectee*)))
4064
4065 (defslimefun pprint-inspector-part (index)
4066 "Pretty-print the currently inspected object."
4067 (with-buffer-syntax ()
4068 (swank-pprint (list (inspector-nth-part index)))))
4069
4070 (defslimefun inspect-in-frame (string index)
4071 (with-buffer-syntax ()
4072 (reset-inspector)
4073 (inspect-object (eval-in-frame (from-string string) index))))
4074
4075 (defslimefun inspect-current-condition ()
4076 (with-buffer-syntax ()
4077 (reset-inspector)
4078 (inspect-object *swank-debugger-condition*)))
4079
4080 (defslimefun inspect-frame-var (frame var)
4081 (with-buffer-syntax ()
4082 (reset-inspector)
4083 (inspect-object (frame-var-value frame var))))
4084
4085
4086 ;;;; Thread listing
4087
4088 (defvar *thread-list* ()
4089 "List of threads displayed in Emacs. We don't care a about
4090 synchronization issues (yet). There can only be one thread listing at
4091 a time.")
4092
4093 (defslimefun list-threads ()
4094 "Return a list ((NAME DESCRIPTION) ...) of all threads."
4095 (setq *thread-list* (all-threads))
4096 (loop for thread in *thread-list*
4097 for name = (thread-name thread)
4098 collect (list (if (symbolp name) (symbol-name name) name)
4099 (thread-status thread)
4100 (thread-id thread))))
4101
4102 (defslimefun quit-thread-browser ()
4103 (setq *thread-list* nil))
4104
4105 (defun nth-thread (index)
4106 (nth index *thread-list*))
4107
4108 (defslimefun debug-nth-thread (index)
4109 (let ((connection *emacs-connection*))
4110 (interrupt-thread (nth-thread index)
4111 (lambda ()
4112 (with-connection (connection)
4113 (simple-break))))))
4114
4115 (defslimefun kill-nth-thread (index)
4116 (kill-thread (nth-thread index)))
4117
4118 (defslimefun start-swank-server-in-thread (index port-file-name)
4119 "Interrupt the INDEXth thread and make it start a swank server.
4120 The server port is written to PORT-FILE-NAME."
4121 (interrupt-thread (nth-thread index)
4122 (lambda ()
4123 (start-server port-file-name :style nil))))
4124
4125 ;;;; Class browser
4126
4127 (defun mop-helper (class-name fn)
4128 (let ((class (find-class class-name nil)))
4129 (if class
4130 (mapcar (lambda (x) (to-string (class-name x)))
4131 (funcall fn class)))))
4132
4133 (defslimefun mop (type symbol-name)
4134 "Return info about classes using mop.
4135
4136 When type is:
4137 :subclasses - return the list of subclasses of class.
4138 :superclasses - return the list of superclasses of class."
4139 (let ((symbol (parse-symbol symbol-name *buffer-package*)))
4140 (ecase type
4141 (:subclasses
4142 (mop-helper symbol #'swank-mop:class-direct-subclasses))
4143 (:superclasses
4144 (mop-helper symbol #'swank-mop:class-direct-superclasses)))))
4145
4146
4147 ;;;; Automatically synchronized state
4148 ;;;
4149 ;;; Here we add hooks to push updates of relevant information to
4150 ;;; Emacs.
4151
4152 ;;;;; *FEATURES*
4153
4154 (defun sync-features-to-emacs ()
4155 "Update Emacs if any relevant Lisp state has changed."
4156 ;; FIXME: *slime-features* should be connection-local
4157 (unless (eq *slime-features* *features*)
4158 (setq *slime-features* *features*)
4159 (send-to-emacs (list :new-features (features-for-emacs)))))
4160
4161 (defun features-for-emacs ()
4162 "Return `*slime-features*' in a format suitable to send it to Emacs."
4163 *slime-features*)
4164
4165 (add-hook *pre-reply-hook* 'sync-features-to-emacs)
4166
4167
4168 ;;;;; Indentation of macros
4169 ;;;
4170 ;;; This code decides how macros should be indented (based on their
4171 ;;; arglists) and tells Emacs. A per-connection cache is used to avoid
4172 ;;; sending redundant information to Emacs -- we just say what's
4173 ;;; changed since last time.
4174 ;;;
4175 ;;; The strategy is to scan all symbols, pick out the macros, and look
4176 ;;; for &body-arguments.
4177
4178 (defvar *configure-emacs-indentation* t
4179 "When true, automatically send indentation information to Emacs
4180 after each command.")
4181
4182 (defslimefun update-indentation-information ()
4183 (perform-indentation-update *emacs-connection* t))
4184
4185 ;; This function is for *PRE-REPLY-HOOK*.
4186 (defun sync-indentation-to-emacs ()
4187 "Send any indentation updates to Emacs via CONNECTION."
4188 (when *configure-emacs-indentation*
4189 (let ((fullp (need-full-indentation-update-p *emacs-connection*)))
4190 (perform-indentation-update *emacs-connection* fullp))))
4191
4192 (defun need-full-indentation-update-p (connection)
4193 "Return true if the whole indentation cache should be updated.
4194 This is a heuristic to avoid scanning all symbols all the time:
4195 instead, we only do a full scan if the set of packages has changed."
4196 (set-difference (list-all-packages)
4197 (connection.indentation-cache-packages connection)))
4198
4199 (defun perform-indentation-update (connection force)
4200 "Update the indentation cache in CONNECTION and update Emacs.
4201 If FORCE is true then start again without considering the old cache."
4202 (let ((cache (connection.indentation-cache connection)))
4203 (when force (clrhash cache))
4204 (let ((delta (update-indentation/delta-for-emacs cache force)))
4205 (setf (connection.indentation-cache-packages connection)
4206 (list-all-packages))
4207 (unless (null delta)
4208 (send-to-emacs (list :indentation-update delta))))))
4209
4210 (defun update-indentation/delta-for-emacs (cache &optional force)
4211 "Update the cache and return the changes in a (SYMBOL . INDENT) list.
4212 If FORCE is true then check all symbols, otherwise only check symbols
4213 belonging to the buffer package."
4214 (let ((alist '()))
4215 (flet ((consider (symbol)
4216 (let ((indent (symbol-indentation symbol)))
4217 (when indent
4218 (unless (equal (gethash symbol cache) indent)
4219 (setf (gethash symbol cache) indent)
4220 (push (cons (string-downcase symbol) indent) alist))))))
4221 (if force
4222 (do-all-symbols (symbol)
4223 (consider symbol))
4224 (do-symbols (symbol *buffer-package*)
4225 (when (eq (symbol-package symbol) *buffer-package*)
4226 (consider symbol)))))
4227 alist))
4228
4229 (defun package-names (package)
4230 "Return the name and all nicknames of PACKAGE in a list."
4231 (cons (package-name package) (package-nicknames package)))
4232