Commit aca95e40 authored by Joao Tavora's avatar Joao Tavora
Browse files

Remove everything presentation-related

parent 37a3ceec
Showing with 0 additions and 2286 deletions
+0 -2286
;;; -*-Emacs-Lisp-*-
;;;%Header
;;; Bridge process filter, V1.0
;;; Copyright (C) 1991 Chris McConnell, ccm@cs.cmu.edu
;;;
;;; Send mail to ilisp@cons.org if you have problems.
;;;
;;; Send mail to majordomo@cons.org if you want to be on the
;;; ilisp mailing list.
;;; This file is part of GNU Emacs.
;;; GNU Emacs is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY. No author or distributor
;;; accepts responsibility to anyone for the consequences of using it
;;; or for whether it serves any particular purpose or works at all,
;;; unless he says so in writing. Refer to the GNU Emacs General Public
;;; License for full details.
;;; Everyone is granted permission to copy, modify and redistribute
;;; GNU Emacs, but only under the conditions described in the
;;; GNU Emacs General Public License. A copy of this license is
;;; supposed to have been given to you along with GNU Emacs so you
;;; can know your rights and responsibilities. It should be in a
;;; file named COPYING. Among other things, the copyright notice
;;; and this notice must be preserved on all copies.
;;; Send any bugs or comments. Thanks to Todd Kaufmann for rewriting
;;; the process filter for continuous handlers.
;;; USAGE: M-x install-bridge will add a process output filter to the
;;; current buffer. Any output that the process does between
;;; bridge-start-regexp and bridge-end-regexp will be bundled up and
;;; passed to the first handler on bridge-handlers that matches the
;;; output using string-match. If bridge-prompt-regexp shows up
;;; before bridge-end-regexp, the bridge will be cancelled. If no
;;; handler matches the output, the first symbol in the output is
;;; assumed to be a buffer name and the rest of the output will be
;;; sent to that buffer's process. This can be used to communicate
;;; between processes or to set up two way interactions between Emacs
;;; and an inferior process.
;;; You can write handlers that process the output in special ways.
;;; See bridge-send-handler for the default handler. The command
;;; hand-bridge is useful for testing. Keep in mind that all
;;; variables are buffer local.
;;; YOUR .EMACS FILE:
;;;
;;; ;;; Set up load path to include bridge
;;; (setq load-path (cons "/bridge-directory/" load-path))
;;; (autoload 'install-bridge "bridge" "Install a process bridge." t)
;;; (setq bridge-hook
;;; '(lambda ()
;;; ;; Example options
;;; (setq bridge-source-insert nil) ;Don't insert in source buffer
;;; (setq bridge-destination-insert nil) ;Don't insert in dest buffer
;;; ;; Handle copy-it messages yourself
;;; (setq bridge-handlers
;;; '(("copy-it" . my-copy-handler)))))
;;; EXAMPLE:
;;; # This pipes stdin to the named buffer in a Unix shell
;;; alias devgnu '(echo -n "\!* "; cat -; echo -n "")'
;;;
;;; ls | devgnu *scratch*
(eval-when-compile
(require 'cl))
;;;%Parameters
(defvar bridge-hook nil
"Hook called when a bridge is installed by install-hook.")
(defvar bridge-start-regexp ""
"*Regular expression to match the start of a process bridge in
process output. It should be followed by a buffer name, the data to
be sent and a bridge-end-regexp.")
(defvar bridge-end-regexp ""
"*Regular expression to match the end of a process bridge in process
output.")
(defvar bridge-prompt-regexp nil
"*Regular expression for detecting a prompt. If there is a
comint-prompt-regexp, it will be initialized to that. A prompt before
a bridge-end-regexp will stop the process bridge.")
(defvar bridge-handlers nil
"Alist of (regexp . handler) for handling process output delimited
by bridge-start-regexp and bridge-end-regexp. The first entry on the
list whose regexp matches the output will be called on the process and
the delimited output.")
(defvar bridge-source-insert t
"*T to insert bridge input in the source buffer minus delimiters.")
(defvar bridge-destination-insert t
"*T for bridge-send-handler to insert bridge input into the
destination buffer minus delimiters.")
(defvar bridge-chunk-size 512
"*Long inputs send to comint processes are broken up into chunks of
this size. If your process is choking on big inputs, try lowering the
value.")
;;;%Internal variables
(defvar bridge-old-filter nil
"Old filter for a bridged process buffer.")
(defvar bridge-string nil
"The current output in the process bridge.")
(defvar bridge-in-progress nil
"The current handler function, if any, that bridge passes strings on to,
or nil if none.")
(defvar bridge-leftovers nil
"Because of chunking you might get an incomplete bridge signal - start but the end is in the next packet. Save the overhanging text here.")
(defvar bridge-send-to-buffer nil
"The buffer that the default bridge-handler (bridge-send-handler) is
currently sending to, or nil if it hasn't started yet. Your handler
function can use this variable also.")
(defvar bridge-last-failure ()
"Last thing that broke the bridge handler. First item is function call
(eval'able); last item is error condition which resulted. This is provided
to help handler-writers in their debugging.")
(defvar bridge-insert-function nil
"If non-nil use this instead of `bridge-insert'")
;;;%Utilities
(defun bridge-insert (output &optional _dummy)
"Insert process OUTPUT into the current buffer."
(if bridge-insert-function
(funcall bridge-insert-function output)
(if output
(let* ((buffer (current-buffer))
(process (get-buffer-process buffer))
(mark (process-mark process))
(window (selected-window))
(at-end nil))
(if (eq (window-buffer window) buffer)
(setq at-end (= (point) mark))
(setq window (get-buffer-window buffer)))
(save-excursion
(goto-char mark)
(insert output)
(set-marker mark (point)))
(if window
(progn
(if at-end (goto-char mark))
(if (not (pos-visible-in-window-p (point) window))
(let ((original (selected-window)))
(save-excursion
(select-window window)
(recenter '(center))
(select-window original))))))))))
;;;
;(defun bridge-send-string (process string)
; "Send PROCESS the contents of STRING as input.
;This is equivalent to process-send-string, except that long input strings
;are broken up into chunks of size comint-input-chunk-size. Processes
;are given a chance to output between chunks. This can help prevent processes
;from hanging when you send them long inputs on some OS's."
; (let* ((len (length string))
; (i (min len bridge-chunk-size)))
; (process-send-string process (substring string 0 i))
; (while (< i len)
; (let ((next-i (+ i bridge-chunk-size)))
; (accept-process-output)
; (process-send-string process (substring string i (min len next-i)))
; (setq i next-i)))))
;;;
(defun bridge-call-handler (handler proc string)
"Funcall HANDLER on PROC, STRING carefully. Error is caught if happens,
and user is signaled. State is put in bridge-last-failure. Returns t if
handler executed without error."
(let ((inhibit-quit nil)
(failed nil))
(condition-case err
(funcall handler proc string)
(error
(ding)
(setq failed t)
(message "bridge-handler \"%s\" failed %s (see bridge-last-failure)"
handler err)
(setq bridge-last-failure
`((funcall ',handler ',proc ,string)
"Caused: "
,err))))
(not failed)))
;;;%Handlers
(defun bridge-send-handler (process input)
"Send PROCESS INPUT to the buffer name found at the start of the
input. The input after the buffer name is sent to the buffer's
process if it has one. If bridge-destination-insert is T, the input
will be inserted into the buffer. If it does not have a process, it
will be inserted at the end of the buffer."
(if (null input)
(setq bridge-send-to-buffer nil) ; end of bridge
(let (buffer-and-start buffer-name dest to)
;; if this is first time, get the buffer out of the first line
(cond ((not bridge-send-to-buffer)
(setq buffer-and-start (read-from-string input)
buffer-name (format "%s" (car (read-from-string input)))
dest (get-buffer buffer-name)
to (get-buffer-process dest)
input (substring input (cdr buffer-and-start)))
(setq bridge-send-to-buffer dest))
(t
(setq buffer-name bridge-send-to-buffer
dest (get-buffer buffer-name)
to (get-buffer-process dest)
)))
(if dest
(let ((buffer (current-buffer)))
(if bridge-destination-insert
(unwind-protect
(progn
(set-buffer dest)
(if to
(bridge-insert process input)
(goto-char (point-max))
(insert input)))
(set-buffer buffer)))
(if to
;; (bridge-send-string to input)
(process-send-string to input)
))
(error "%s is not a buffer" buffer-name)))))
;;;%Filter
(defun bridge-filter (process output)
"Given PROCESS and some OUTPUT, check for the presence of
bridge-start-regexp. Everything prior to this will be passed to the
normal filter function or inserted in the buffer if it is nil. The
output up to bridge-end-regexp will be sent to the first handler on
bridge-handlers that matches the string. If no handlers match, the
input will be sent to bridge-send-handler. If bridge-prompt-regexp is
encountered before the bridge-end-regexp, the bridge will be cancelled."
(let ((inhibit-quit t)
(match-data (match-data))
(buffer (current-buffer))
(process-buffer (process-buffer process))
(case-fold-search t)
(start 0) (end 0)
function
b-start b-start-end b-end)
(set-buffer process-buffer) ;; access locals
;; Handle bridge messages that straddle a packet by prepending
;; them to this packet.
(when bridge-leftovers
(setq output (concat bridge-leftovers output))
(setq bridge-leftovers nil))
(setq function bridge-in-progress)
;; How it works:
;;
;; start, end delimit the part of string we are interested in;
;; initially both 0; after an iteration we move them to next string.
;; b-start, b-end delimit part of string to bridge (possibly whole string);
;; this will be string between corresponding regexps.
;; There are two main cases when we come into loop:
;; bridge in progress
;;0 setq b-start = start
;;1 setq b-end (or end-pattern end)
;;4 process string
;;5 remove handler if end found
;; no bridge in progress
;;0 setq b-start if see start-pattern
;;1 setq b-end if bstart to (or end-pattern end)
;;2 send (substring start b-start) to normal place
;;3 find handler (in b-start, b-end) if not set
;;4 process string
;;5 remove handler if end found
;; equivalent sections have the same numbers here;
;; we fold them together in this code.
(block bridge-filter
(unwind-protect
(while (< end (length output))
;;0 setq b-start if find
(setq b-start
(cond (bridge-in-progress
(setq b-start-end start)
start)
((string-match bridge-start-regexp output start)
(setq b-start-end (match-end 0))
(match-beginning 0))
(t nil)))
;;1 setq b-end
(setq b-end
(if b-start
(let ((end-seen (string-match bridge-end-regexp
output b-start-end)))
(if end-seen (setq end (match-end 0)))
end-seen)))
;; Detect and save partial bridge messages
(when (and b-start b-start-end (not b-end))
(setq bridge-leftovers (substring output b-start))
)
(if (and b-start (not b-end))
(setq end b-start)
(if (not b-end)
(setq end (length output))))
;;1.5 - if see prompt before end, remove current
(if (and b-start b-end)
(let ((prompt (string-match bridge-prompt-regexp
output b-start-end)))
(if (and prompt (<= (match-end 0) b-end))
(setq b-start nil ; b-start-end start
b-end start
end (match-end 0)
bridge-in-progress nil
))))
;;2 send (substring start b-start) to old filter, if any
(when (not (equal start (or b-start end))) ; don't bother on empty string
(let ((pass-on (substring output start (or b-start end))))
(if bridge-old-filter
(let ((old bridge-old-filter))
(store-match-data match-data)
(funcall old process pass-on)
;; if filter changed, re-install ourselves
(let ((new (process-filter process)))
(if (not (eq new 'bridge-filter))
(progn (setq bridge-old-filter new)
(set-process-filter process 'bridge-filter)))))
(set-buffer process-buffer)
(bridge-insert pass-on))))
(if (and b-start-end (not b-end))
(return-from bridge-filter t) ; when last bit has prematurely ending message, exit early.
(progn
;;3 find handler (in b-start, b-end) if none current
(if (and b-start (not bridge-in-progress))
(let ((handlers bridge-handlers))
(while (and handlers (not function))
(let* ((handler (car handlers))
(m (string-match (car handler) output b-start-end)))
(if (and m (< m b-end))
(setq function (cdr handler))
(setq handlers (cdr handlers)))))
;; Set default handler if none
(if (null function)
(setq function 'bridge-send-handler))
(setq bridge-in-progress function)))
;;4 process strin
(if function
(let ((ok t))
(if (/= b-start-end b-end)
(let ((send (substring output b-start-end b-end)))
;; also, insert the stuff in buffer between
;; iff bridge-source-insert.
(if bridge-source-insert (bridge-insert send))
;; call handler on string
(setq ok (bridge-call-handler function process send))))
;;5 remove handler if end found
;; if function removed then tell it that's all
(if (or (not ok) (/= b-end end)) ;; saw end before end-of-string
(progn
(bridge-call-handler function process nil)
;; have to remove function too for next time around
(setq function nil
bridge-in-progress nil)
))
))
;; continue looping, in case there's more string
(setq start end))
))
;; protected forms: restore buffer, match-data
(set-buffer buffer)
(store-match-data match-data)
))))
;;;%Interface
(defun install-bridge ()
"Set up a process bridge in the current buffer."
(interactive)
(if (not (get-buffer-process (current-buffer)))
(error "%s does not have a process" (buffer-name (current-buffer)))
(make-local-variable 'bridge-start-regexp)
(make-local-variable 'bridge-end-regexp)
(make-local-variable 'bridge-prompt-regexp)
(make-local-variable 'bridge-handlers)
(make-local-variable 'bridge-source-insert)
(make-local-variable 'bridge-destination-insert)
(make-local-variable 'bridge-chunk-size)
(make-local-variable 'bridge-old-filter)
(make-local-variable 'bridge-string)
(make-local-variable 'bridge-in-progress)
(make-local-variable 'bridge-send-to-buffer)
(make-local-variable 'bridge-leftovers)
(setq bridge-string nil bridge-in-progress nil
bridge-send-to-buffer nil)
(if (boundp 'comint-prompt-regexp)
(setq bridge-prompt-regexp comint-prompt-regexp))
(let ((process (get-buffer-process (current-buffer))))
(if process
(if (not (eq (process-filter process) 'bridge-filter))
(progn
(setq bridge-old-filter (process-filter process))
(set-process-filter process 'bridge-filter)))
(error "%s does not have a process"
(buffer-name (current-buffer)))))
(run-hooks 'bridge-hook)
(message "Process bridge is installed")))
;;;
(defun reset-bridge ()
"Must be called from the process's buffer. Removes any active bridge."
(interactive)
;; for when things get wedged
(if bridge-in-progress
(unwind-protect
(funcall bridge-in-progress (get-buffer-process
(current-buffer))
nil)
(setq bridge-in-progress nil))
(message "No bridge in progress.")))
;;;
(defun remove-bridge ()
"Remove bridge from the current buffer."
(interactive)
(let ((process (get-buffer-process (current-buffer))))
(if (or (not process) (not (eq (process-filter process) 'bridge-filter)))
(error "%s has no bridge" (buffer-name (current-buffer)))
;; remove any bridge-in-progress
(reset-bridge)
(set-process-filter process bridge-old-filter)
(funcall bridge-old-filter process bridge-string)
(message "Process bridge is removed."))))
;;;% Utility for testing
(defun hand-bridge (start end)
"With point at bridge-start, sends bridge-start + string +
bridge-end to bridge-filter. With prefix, use current region to send."
(interactive "r")
(let ((p0 (if current-prefix-arg (min start end)
(if (looking-at bridge-start-regexp) (point)
(error "Not looking at bridge-start-regexp"))))
(p1 (if current-prefix-arg (max start end)
(if (re-search-forward bridge-end-regexp nil t)
(point) (error "Didn't see bridge-end-regexp")))))
(bridge-filter (get-buffer-process (current-buffer))
(buffer-substring-no-properties p0 p1))
))
(provide 'bridge)
(eval-and-compile
(require 'sly))
(define-sly-contrib sly-presentation-streams
"Streams that allow attaching object identities to portions of
output."
(:authors "Alan Ruttenberg <alanr-l@mumble.net>"
"Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>"
"Helmut Eller <heller@common-lisp.net>")
(:license "GPL")
(:swank-dependencies swank-presentation-streams))
(provide 'sly-presentation-streams)
This diff is collapsed.
;;; swank-presentation-streams.lisp --- Streams that allow attaching object identities
;;; to portions of output
;;;
;;; Authors: Alan Ruttenberg <alanr-l@mumble.net>
;;; Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>
;;; Helmut Eller <heller@common-lisp.net>
;;;
;;; License: This code has been placed in the Public Domain. All warranties
;;; are disclaimed.
(in-package :swank)
(swank-require :swank-presentations)
;; This file contains a mechanism for printing to the sly repl so
;; that the printed result remembers what object it is associated
;; with. This extends the recording of REPL results.
;;
;; There are two methods:
;;
;; 1. Depends on the ilisp bridge code being installed and ready to
;; intercept messages in the printed stream. We encode the
;; information with a message saying that we are starting to print
;; an object corresponding to a given id and another when we are
;; done. The process filter notices these and adds the necessary
;; text properties to the output.
;;
;; 2. Use separate protocol messages :presentation-start and
;; :presentation-end for sending presentations.
;;
;; We only do this if we know we are printing to a sly stream,
;; checked with the method sly-stream-p. Initially this checks for
;; the knows sly streams looking at *connections*. In cmucl, sbcl, and
;; openmcl it also checks if it is a pretty-printing stream which
;; ultimately prints to a sly stream.
;;
;; Method 1 seems to be faster, but the printed escape sequences can
;; disturb the column counting, and thus the layout in pretty-printing.
;; We use method 1 when a dedicated output stream is used.
;;
;; Method 2 is cleaner and works with pretty printing if the pretty
;; printers support "annotations". We use method 2 when no dedicated
;; output stream is used.
;; Control
(defvar *enable-presenting-readable-objects* t
"set this to enable automatically printing presentations for some
subset of readable objects, such as pathnames." )
;; doing it
(defmacro presenting-object (object stream &body body)
"What you use in your code. Wrap this around some printing and that text will
be sensitive and remember what object it is in the repl"
`(presenting-object-1 ,object ,stream #'(lambda () ,@body)))
(defmacro presenting-object-if (predicate object stream &body body)
"What you use in your code. Wrap this around some printing and that text will
be sensitive and remember what object it is in the repl if predicate is true"
(let ((continue (gensym)))
`(let ((,continue #'(lambda () ,@body)))
(if ,predicate
(presenting-object-1 ,object ,stream ,continue)
(funcall ,continue)))))
;;; Get pretty printer patches for SBCL at load (not compile) time.
#+sbcl
(eval-when (:load-toplevel)
(handler-bind ((simple-error
(lambda (c)
(declare (ignore c))
(let ((clobber-it (find-restart 'sb-kernel::clobber-it)))
(when clobber-it (invoke-restart clobber-it))))))
(sb-ext:without-package-locks
(swank-backend::with-debootstrapping
(load (make-pathname
:name "sbcl-pprint-patch"
:type "lisp"
:directory (pathname-directory swank-loader:*source-directory*)))))))
(let ((last-stream nil)
(last-answer nil))
(defun sly-stream-p (stream)
"Check if stream is one of the sly streams, since if it isn't we
don't want to present anything.
Two special return values:
:DEDICATED -- Output ends up on a dedicated output stream
:REPL-RESULT -- Output ends up on the :repl-results target.
"
(if (eq last-stream stream)
last-answer
(progn
(setq last-stream stream)
(if (eq stream t)
(setq stream *standard-output*))
(setq last-answer
(or #+openmcl
(and (typep stream 'ccl::xp-stream)
;(sly-stream-p (ccl::xp-base-stream (slot-value stream 'ccl::xp-structure)))
(sly-stream-p (ccl::%svref (slot-value stream 'ccl::xp-structure) 1)))
#+cmu
(or (and (typep stream 'lisp::indenting-stream)
(sly-stream-p (lisp::indenting-stream-stream stream)))
(and (typep stream 'pretty-print::pretty-stream)
(fboundp 'pretty-print::enqueue-annotation)
(let ((sly-stream-p
(sly-stream-p (pretty-print::pretty-stream-target stream))))
(and ;; Printing through CMUCL pretty
;; streams is only cleanly
;; possible if we are using the
;; bridge-less protocol with
;; annotations, because the bridge
;; escape sequences disturb the
;; pretty printer layout.
(not (eql sly-stream-p :dedicated-output))
;; If OK, return the return value
;; we got from sly-stream-p on
;; the target stream (could be
;; :repl-result):
sly-stream-p))))
#+sbcl
(let ()
(declare (notinline sb-pretty::pretty-stream-target))
(and (typep stream (find-symbol "PRETTY-STREAM" 'sb-pretty))
(find-symbol "ENQUEUE-ANNOTATION" 'sb-pretty)
(not *use-dedicated-output-stream*)
(sly-stream-p (sb-pretty::pretty-stream-target stream))))
#+allegro
(and (typep stream 'excl:xp-simple-stream)
(sly-stream-p (excl::stream-output-handle stream)))
(loop for connection in *connections*
thereis (or (and (eq stream (connection.dedicated-output connection))
:dedicated)
(eq stream (connection.socket-io connection))
(eq stream (connection.user-output connection))
(eq stream (connection.user-io connection))
(and (eq stream (connection.repl-results connection))
:repl-result)))))))))
(defun can-present-readable-objects (&optional stream)
(declare (ignore stream))
*enable-presenting-readable-objects*)
;; If we are printing to an XP (pretty printing) stream, printing the
;; escape sequences directly would mess up the layout because column
;; counting is disturbed. Use "annotations" instead.
#+allegro
(defun write-annotation (stream function arg)
(if (typep stream 'excl:xp-simple-stream)
(excl::schedule-annotation stream function arg)
(funcall function arg stream nil)))
#+cmu
(defun write-annotation (stream function arg)
(if (and (typep stream 'pp:pretty-stream)
(fboundp 'pp::enqueue-annotation))
(pp::enqueue-annotation stream function arg)
(funcall function arg stream nil)))
#+sbcl
(defun write-annotation (stream function arg)
(let ((enqueue-annotation
(find-symbol "ENQUEUE-ANNOTATION" 'sb-pretty)))
(if (and enqueue-annotation
(typep stream (find-symbol "PRETTY-STREAM" 'sb-pretty)))
(funcall enqueue-annotation stream function arg)
(funcall function arg stream nil))))
#-(or allegro cmu sbcl)
(defun write-annotation (stream function arg)
(funcall function arg stream nil))
(defstruct presentation-record
(id)
(printed-p)
(target))
(defun presentation-start (record stream truncatep)
(unless truncatep
;; Don't start new presentations when nothing is going to be
;; printed due to *print-lines*.
(let ((pid (presentation-record-id record))
(target (presentation-record-target record)))
(case target
(:dedicated
;; Use bridge protocol
(write-string "<" stream)
(prin1 pid stream)
(write-string "" stream))
(t
(finish-output stream)
(send-to-emacs `(:presentation-start ,pid ,target)))))
(setf (presentation-record-printed-p record) t)))
(defun presentation-end (record stream truncatep)
(declare (ignore truncatep))
;; Always end old presentations that were started.
(when (presentation-record-printed-p record)
(let ((pid (presentation-record-id record))
(target (presentation-record-target record)))
(case target
(:dedicated
;; Use bridge protocol
(write-string ">" stream)
(prin1 pid stream)
(write-string "" stream))
(t
(finish-output stream)
(send-to-emacs `(:presentation-end ,pid ,target)))))))
(defun presenting-object-1 (object stream continue)
"Uses the bridge mechanism with two messages >id and <id. The first one
says that I am starting to print an object with this id. The second says I am finished"
;; this declare special is to let the compiler know that *record-repl-results* will eventually be
;; a global special, even if it isn't when this file is compiled/loaded.
(declare (special *record-repl-results*))
(let ((sly-stream-p
(and *record-repl-results* (sly-stream-p stream))))
(if sly-stream-p
(let* ((pid (swank::save-presented-object object))
(record (make-presentation-record :id pid :printed-p nil
:target (if (eq sly-stream-p :repl-result)
:repl-result
nil))))
(write-annotation stream #'presentation-start record)
(multiple-value-prog1
(funcall continue)
(write-annotation stream #'presentation-end record)))
(funcall continue))))
(defun present-repl-results-via-presentation-streams (values)
;; Override a function in swank.lisp, so that
;; nested presentations work in the REPL result.
(let ((repl-results (connection.repl-results *emacs-connection*)))
(flet ((send (value)
(presenting-object value repl-results
(prin1 value repl-results))
(terpri repl-results)))
(if (null values)
(progn
(princ "; No value" repl-results)
(terpri repl-results))
(mapc #'send values)))
(finish-output repl-results)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Example: Tell openmcl and cmucl to always present unreadable objects. try (describe 'class)
#+openmcl
(in-package :ccl)
#+openmcl
(let ((*warn-if-redefine-kernel* nil)
(*warn-if-redefine* nil))
(defun %print-unreadable-object (object stream type id thunk)
(cond ((null stream) (setq stream *standard-output*))
((eq stream t) (setq stream *terminal-io*)))
(swank::presenting-object object stream
(write-unreadable-start object stream)
(when type
(princ (type-of object) stream)
(stream-write-char stream #\space))
(when thunk
(funcall thunk))
(if id
(%write-address object stream #\>)
(pp-end-block stream ">"))
nil))
(defmethod print-object :around ((pathname pathname) stream)
(swank::presenting-object-if
(swank::can-present-readable-objects stream)
pathname stream (call-next-method))))
#+openmcl
(ccl::def-load-pointers clear-presentations ()
(swank::clear-presentation-tables))
(in-package :swank)
#+cmu
(progn
(fwrappers:define-fwrapper presenting-unreadable-wrapper (object stream type identity body)
(presenting-object object stream
(fwrappers:call-next-function)))
(fwrappers:define-fwrapper presenting-pathname-wrapper (pathname stream depth)
(presenting-object-if (can-present-readable-objects stream) pathname stream
(fwrappers:call-next-function)))
(fwrappers::fwrap 'lisp::%print-pathname #'presenting-pathname-wrapper)
(fwrappers::fwrap 'lisp::%print-unreadable-object #'presenting-unreadable-wrapper)
)
#+sbcl
(progn
(defvar *saved-%print-unreadable-object*
(fdefinition 'sb-impl::%print-unreadable-object))
(sb-ext:without-package-locks
(setf (fdefinition 'sb-impl::%print-unreadable-object)
(lambda (object stream type identity body)
(presenting-object object stream
(funcall *saved-%print-unreadable-object*
object stream type identity body))))
(defmethod print-object :around ((object pathname) stream)
(presenting-object object stream
(call-next-method)))))
#+allegro
(progn
(excl:def-fwrapper presenting-unreadable-wrapper (object stream type identity continuation)
(swank::presenting-object object stream (excl:call-next-fwrapper)))
(excl:def-fwrapper presenting-pathname-wrapper (pathname stream depth)
(presenting-object-if (can-present-readable-objects stream) pathname stream
(excl:call-next-fwrapper)))
(excl:fwrap 'excl::print-unreadable-object-1
'print-unreadable-present 'presenting-unreadable-wrapper)
(excl:fwrap 'excl::pathname-printer
'print-pathname-present 'presenting-pathname-wrapper))
;; Hook into SWANK.
(setq *send-repl-results-function* 'present-repl-results-via-presentation-streams)
(provide :swank-presentation-streams)
;;; swank-presentations.lisp --- imitate LispM's presentations
;;
;; Authors: Alan Ruttenberg <alanr-l@mumble.net>
;; Luke Gorrie <luke@synap.se>
;; Helmut Eller <heller@common-lisp.net>
;; Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>
;;
;; License: This code has been placed in the Public Domain. All warranties
;; are disclaimed.
;;
(in-package :swank)
;;;; Recording and accessing results of computations
(defvar *record-repl-results* t
"Non-nil means that REPL results are saved for later lookup.")
(defvar *object-to-presentation-id*
(make-weak-key-hash-table :test 'eq)
"Store the mapping of objects to numeric identifiers")
(defvar *presentation-id-to-object*
(make-weak-value-hash-table :test 'eql)
"Store the mapping of numeric identifiers to objects")
(defun clear-presentation-tables ()
(clrhash *object-to-presentation-id*)
(clrhash *presentation-id-to-object*))
(defvar *presentation-counter* 0 "identifier counter")
(defvar *nil-surrogate* (make-symbol "nil-surrogate"))
;; XXX thread safety? [2006-09-13] mb: not in the slightest (fwiw the
;; rest of sly isn't thread safe either), do we really care?
(defun save-presented-object (object)
"Save OBJECT and return the assigned id.
If OBJECT was saved previously return the old id."
(let ((object (if (null object) *nil-surrogate* object)))
;; We store *nil-surrogate* instead of nil, to distinguish it from
;; an object that was garbage collected.
(or (gethash object *object-to-presentation-id*)
(let ((id (incf *presentation-counter*)))
(setf (gethash id *presentation-id-to-object*) object)
(setf (gethash object *object-to-presentation-id*) id)
id))))
(defslyfun lookup-presented-object (id)
"Retrieve the object corresponding to ID.
The secondary value indicates the absence of an entry."
(etypecase id
(integer
;;
(multiple-value-bind (object foundp)
(gethash id *presentation-id-to-object*)
(cond
((eql object *nil-surrogate*)
;; A stored nil object
(values nil t))
((null object)
;; Object that was replaced by nil in the weak hash table
;; when the object was garbage collected.
(values nil nil))
(t
(values object foundp)))))
(cons
(destructure-case id
((:frame-var thread-id frame index)
(declare (ignore thread-id)) ; later
(handler-case
(frame-var-value frame index)
(t (condition)
(declare (ignore condition))
(values nil nil))
(:no-error (value)
(values value t))))
((:inspected-part part-index)
(inspector-nth-part part-index))))))
(defslyfun lookup-presented-object-or-lose (id)
"Get the result of the previous REPL evaluation with ID."
(multiple-value-bind (object foundp) (lookup-presented-object id)
(cond (foundp object)
(t (error "Attempt to access unrecorded object (id ~D)." id)))))
(defslyfun clear-repl-results ()
"Forget the results of all previous REPL evaluations."
(clear-presentation-tables)
t)
(defun present-repl-results (values)
;; Override a function in swank.lisp, so that
;; presentations are associated with every REPL result.
(flet ((send (value)
(let ((id (and *record-repl-results*
(save-presented-object value))))
(send-to-emacs `(:presentation-start ,id :repl-result))
(send-to-emacs `(:write-string ,(prin1-to-string value)
:repl-result))
(send-to-emacs `(:presentation-end ,id :repl-result))
(send-to-emacs `(:write-string ,(string #\Newline)
:repl-result)))))
(fresh-line)
(finish-output)
(if (null values)
(send-to-emacs `(:write-string "; No value" :repl-result))
(mapc #'send values))))
;;;; Presentation menu protocol
;;
;; To define a menu for a type of object, define a method
;; menu-choices-for-presentation on that object type. This function
;; should return a list of two element lists where the first element is
;; the name of the menu action and the second is a function that will be
;; called if the menu is chosen. The function will be called with 3
;; arguments:
;;
;; choice: The string naming the action from above
;;
;; object: The object
;;
;; id: The presentation id of the object
;;
;; You might want append (when (next-method-p) (call-next-method)) to
;; pick up the Menu actions of superclasses.
;;
(defvar *presentation-active-menu* nil)
(defun menu-choices-for-presentation-id (id)
(multiple-value-bind (ob presentp) (lookup-presented-object id)
(cond ((not presentp) 'not-present)
(t
(let ((menu-and-actions (menu-choices-for-presentation ob)))
(setq *presentation-active-menu* (cons id menu-and-actions))
(mapcar 'car menu-and-actions))))))
(defun swank-ioify (thing)
(cond ((keywordp thing) thing)
((and (symbolp thing)(not (find #\: (symbol-name thing))))
(intern (symbol-name thing) 'swank-io-package))
((consp thing) (cons (swank-ioify (car thing)) (swank-ioify (cdr thing))))
(t thing)))
(defun execute-menu-choice-for-presentation-id (id count item)
(let ((ob (lookup-presented-object id)))
(assert (equal id (car *presentation-active-menu*)) ()
"Bug: Execute menu call for id ~a but menu has id ~a"
id (car *presentation-active-menu*))
(let ((action (second (nth (1- count) (cdr *presentation-active-menu*)))))
(swank-ioify (funcall action item ob id)))))
(defgeneric menu-choices-for-presentation (object)
(:method (ob) (declare (ignore ob)) nil)) ; default method
;; Pathname
(defmethod menu-choices-for-presentation ((ob pathname))
(let* ((file-exists (ignore-errors (probe-file ob)))
(lisp-type (make-pathname :type "lisp"))
(source-file (and (not (member (pathname-type ob) '("lisp" "cl") :test 'equal))
(let ((source (merge-pathnames lisp-type ob)))
(and (ignore-errors (probe-file source))
source))))
(fasl-file (and file-exists
(equal (ignore-errors
(namestring
(truename
(compile-file-pathname
(merge-pathnames lisp-type ob)))))
(namestring (truename ob))))))
(remove nil
(list*
(and (and file-exists (not fasl-file))
(list "Edit this file"
(lambda(choice object id)
(declare (ignore choice id))
(ed-in-emacs (namestring (truename object)))
nil)))
(and file-exists
(list "Dired containing directory"
(lambda (choice object id)
(declare (ignore choice id))
(ed-in-emacs (namestring
(truename
(merge-pathnames
(make-pathname :name "" :type "") object))))
nil)))
(and fasl-file
(list "Load this fasl file"
(lambda (choice object id)
(declare (ignore choice id object))
(load ob)
nil)))
(and fasl-file
(list "Delete this fasl file"
(lambda (choice object id)
(declare (ignore choice id object))
(let ((nt (namestring (truename ob))))
(when (y-or-n-p-in-emacs "Delete ~a? " nt)
(delete-file nt)))
nil)))
(and source-file
(list "Edit lisp source file"
(lambda (choice object id)
(declare (ignore choice id object))
(ed-in-emacs (namestring (truename source-file)))
nil)))
(and source-file
(list "Load lisp source file"
(lambda(choice object id)
(declare (ignore choice id object))
(load source-file)
nil)))
(and (next-method-p) (call-next-method))))))
(defmethod menu-choices-for-presentation ((ob function))
(list (list "Disassemble"
(lambda (choice object id)
(declare (ignore choice id))
(disassemble object)))))
(defslyfun inspect-presentation (id reset-p)
(let ((what (lookup-presented-object-or-lose id)))
(when reset-p
(reset-inspector))
(inspect-object what)))
(setq *send-repl-results-function* 'present-repl-results)
(provide :swank-presentations)
(require 'sly-presentations)
(require 'sly-tests)
(require 'sly-repl-tests "test/sly-repl-tests")
(define-sly-ert-test pick-up-presentation-at-point ()
"Ensure presentations are found consistently."
(cl-labels ((assert-it (point &optional negate)
(let ((result
(cl-first
(sly-presentation-around-or-before-point point))))
(unless (if negate (not result) result)
(ert-fail
(format "Failed to pick up presentation at point %s"
point))))))
(with-temp-buffer
(sly-insert-presentation "1234567890" `(:inspected-part 42))
(insert " ")
(assert-it 1)
(assert-it 2)
(assert-it 3)
(assert-it 4)
(assert-it 5)
(assert-it 10)
(assert-it 11)
(assert-it 12 t))))
(def-sly-test (pretty-presentation-results (:fails-for "allegro"))
(input result-contents)
"Test some more simple situations dealing with print-width and stuff.
Very much like `repl-test-2', but should be more stable when
presentations are enabled, except in allegro."
'(("(with-standard-io-syntax
(write (make-list 15 :initial-element '(1 . 2)) :pretty t) 0)"
"SWANK> (with-standard-io-syntax
(write (make-list 15 :initial-element '(1 . 2)) :pretty t) 0)
{((1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2)
(1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2))
}0
SWANK> *[]")
;; Two times to test the effect of FRESH-LINE.
("(with-standard-io-syntax
(write (make-list 15 :initial-element '(1 . 2)) :pretty t) 0)"
"SWANK> (with-standard-io-syntax
(write (make-list 15 :initial-element '(1 . 2)) :pretty t) 0)
{((1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2)
(1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2) (1 . 2))
}0
SWANK> *[]"))
(sly-test-repl-test input result-contents))
(provide 'sly-presentations-tests)
;; Pretty printer patch for SBCL, which adds the "annotations" feature
;; required for sending presentations through pretty-printing streams.
;;
;; The section marked "Changed functions" and the DEFSTRUCT
;; PRETTY-STREAM are based on SBCL's pprint.lisp.
;;
;; Public domain.
(in-package "SB!PRETTY")
(defstruct (annotation (:include queued-op))
(handler (constantly nil) :type function)
(record))
(defstruct (pretty-stream (:include sb!kernel:ansi-stream
(out #'pretty-out)
(sout #'pretty-sout)
(misc #'pretty-misc))
(:constructor make-pretty-stream (target))
(:copier nil))
;; Where the output is going to finally go.
(target (missing-arg) :type stream)
;; Line length we should format to. Cached here so we don't have to keep
;; extracting it from the target stream.
(line-length (or *print-right-margin*
(sb!impl::line-length target)
default-line-length)
:type column)
;; A simple string holding all the text that has been output but not yet
;; printed.
(buffer (make-string initial-buffer-size) :type (simple-array character (*)))
;; The index into BUFFER where more text should be put.
(buffer-fill-pointer 0 :type index)
;; Whenever we output stuff from the buffer, we shift the remaining noise
;; over. This makes it difficult to keep references to locations in
;; the buffer. Therefore, we have to keep track of the total amount of
;; stuff that has been shifted out of the buffer.
(buffer-offset 0 :type posn)
;; The column the first character in the buffer will appear in. Normally
;; zero, but if we end up with a very long line with no breaks in it we
;; might have to output part of it. Then this will no longer be zero.
(buffer-start-column (or (sb!impl::charpos target) 0) :type column)
;; The line number we are currently on. Used for *PRINT-LINES*
;; abbreviations and to tell when sections have been split across
;; multiple lines.
(line-number 0 :type index)
;; the value of *PRINT-LINES* captured at object creation time. We
;; use this, instead of the dynamic *PRINT-LINES*, to avoid
;; weirdness like
;; (let ((*print-lines* 50))
;; (pprint-logical-block ..
;; (dotimes (i 10)
;; (let ((*print-lines* 8))
;; (print (aref possiblybigthings i) prettystream)))))
;; terminating the output of the entire logical blockafter 8 lines.
(print-lines *print-lines* :type (or index null) :read-only t)
;; Stack of logical blocks in effect at the buffer start.
(blocks (list (make-logical-block)) :type list)
;; Buffer holding the per-line prefix active at the buffer start.
;; Indentation is included in this. The length of this is stored
;; in the logical block stack.
(prefix (make-string initial-buffer-size) :type (simple-array character (*)))
;; Buffer holding the total remaining suffix active at the buffer start.
;; The characters are right-justified in the buffer to make it easier
;; to output the buffer. The length is stored in the logical block
;; stack.
(suffix (make-string initial-buffer-size) :type (simple-array character (*)))
;; Queue of pending operations. When empty, HEAD=TAIL=NIL. Otherwise,
;; TAIL holds the first (oldest) cons and HEAD holds the last (newest)
;; cons. Adding things to the queue is basically (setf (cdr head) (list
;; new)) and removing them is basically (pop tail) [except that care must
;; be taken to handle the empty queue case correctly.]
(queue-tail nil :type list)
(queue-head nil :type list)
;; Block-start queue entries in effect at the queue head.
(pending-blocks nil :type list)
;; Queue of annotations to the buffer
(annotations-tail nil :type list)
(annotations-head nil :type list))
(defmacro enqueue (stream type &rest args)
(let ((constructor (intern (concatenate 'string
"MAKE-"
(symbol-name type))
"SB-PRETTY")))
(once-only ((stream stream)
(entry `(,constructor :posn
(index-posn
(pretty-stream-buffer-fill-pointer
,stream)
,stream)
,@args))
(op `(list ,entry))
(head `(pretty-stream-queue-head ,stream)))
`(progn
(if ,head
(setf (cdr ,head) ,op)
(setf (pretty-stream-queue-tail ,stream) ,op))
(setf (pretty-stream-queue-head ,stream) ,op)
,entry))))
;;;
;;; New helper functions
;;;
(defun enqueue-annotation (stream handler record)
(enqueue stream annotation :handler handler
:record record))
(defun re-enqueue-annotation (stream annotation)
(let* ((annotation-cons (list annotation))
(head (pretty-stream-annotations-head stream)))
(if head
(setf (cdr head) annotation-cons)
(setf (pretty-stream-annotations-tail stream) annotation-cons))
(setf (pretty-stream-annotations-head stream) annotation-cons)
nil))
(defun re-enqueue-annotations (stream end)
(loop for tail = (pretty-stream-queue-tail stream) then (cdr tail)
while (and tail (not (eql (car tail) end)))
when (annotation-p (car tail))
do (re-enqueue-annotation stream (car tail))))
(defun dequeue-annotation (stream &key end-posn)
(let ((next-annotation (car (pretty-stream-annotations-tail stream))))
(when next-annotation
(when (or (not end-posn)
(<= (annotation-posn next-annotation) end-posn))
(pop (pretty-stream-annotations-tail stream))
(unless (pretty-stream-annotations-tail stream)
(setf (pretty-stream-annotations-head stream) nil))
next-annotation))))
(defun invoke-annotation (stream annotation truncatep)
(let ((target (pretty-stream-target stream)))
(funcall (annotation-handler annotation)
(annotation-record annotation)
target
truncatep)))
(defun output-buffer-with-annotations (stream end)
(let ((target (pretty-stream-target stream))
(buffer (pretty-stream-buffer stream))
(end-posn (index-posn end stream))
(start 0))
(loop
for annotation = (dequeue-annotation stream :end-posn end-posn)
while annotation
do
(let ((annotation-index (posn-index (annotation-posn annotation)
stream)))
(when (> annotation-index start)
(write-string buffer target :start start
:end annotation-index)
(setf start annotation-index))
(invoke-annotation stream annotation nil)))
(when (> end start)
(write-string buffer target :start start :end end))))
(defun flush-annotations (stream end truncatep)
(let ((end-posn (index-posn end stream)))
(loop
for annotation = (dequeue-annotation stream :end-posn end-posn)
while annotation
do (invoke-annotation stream annotation truncatep))))
;;;
;;; Changed functions
;;;
(defun maybe-output (stream force-newlines-p)
(declare (type pretty-stream stream))
(let ((tail (pretty-stream-queue-tail stream))
(output-anything nil))
(loop
(unless tail
(setf (pretty-stream-queue-head stream) nil)
(return))
(let ((next (pop tail)))
(etypecase next
(newline
(when (ecase (newline-kind next)
((:literal :mandatory :linear) t)
(:miser (misering-p stream))
(:fill
(or (misering-p stream)
(> (pretty-stream-line-number stream)
(logical-block-section-start-line
(first (pretty-stream-blocks stream))))
(ecase (fits-on-line-p stream
(newline-section-end next)
force-newlines-p)
((t) nil)
((nil) t)
(:dont-know
(return))))))
(setf output-anything t)
(output-line stream next)))
(indentation
(unless (misering-p stream)
(set-indentation stream
(+ (ecase (indentation-kind next)
(:block
(logical-block-start-column
(car (pretty-stream-blocks stream))))
(:current
(posn-column
(indentation-posn next)
stream)))
(indentation-amount next)))))
(block-start
(ecase (fits-on-line-p stream (block-start-section-end next)
force-newlines-p)
((t)
;; Just nuke the whole logical block and make it look like one
;; nice long literal. (But don't nuke annotations.)
(let ((end (block-start-block-end next)))
(expand-tabs stream end)
(re-enqueue-annotations stream end)
(setf tail (cdr (member end tail)))))
((nil)
(really-start-logical-block
stream
(posn-column (block-start-posn next) stream)
(block-start-prefix next)
(block-start-suffix next)))
(:dont-know
(return))))
(block-end
(really-end-logical-block stream))
(tab
(expand-tabs stream next))
(annotation
(re-enqueue-annotation stream next))))
(setf (pretty-stream-queue-tail stream) tail))
output-anything))
(defun output-line (stream until)
(declare (type pretty-stream stream)
(type newline until))
(let* ((target (pretty-stream-target stream))
(buffer (pretty-stream-buffer stream))
(kind (newline-kind until))
(literal-p (eq kind :literal))
(amount-to-consume (posn-index (newline-posn until) stream))
(amount-to-print
(if literal-p
amount-to-consume
(let ((last-non-blank
(position #\space buffer :end amount-to-consume
:from-end t :test #'char/=)))
(if last-non-blank
(1+ last-non-blank)
0)))))
(output-buffer-with-annotations stream amount-to-print)
(flush-annotations stream amount-to-consume nil)
(let ((line-number (pretty-stream-line-number stream)))
(incf line-number)
(when (and (not *print-readably*)
(pretty-stream-print-lines stream)
(>= line-number (pretty-stream-print-lines stream)))
(write-string " .." target)
(flush-annotations stream
(pretty-stream-buffer-fill-pointer stream)
t)
(let ((suffix-length (logical-block-suffix-length
(car (pretty-stream-blocks stream)))))
(unless (zerop suffix-length)
(let* ((suffix (pretty-stream-suffix stream))
(len (length suffix)))
(write-string suffix target
:start (- len suffix-length)
:end len))))
(throw 'line-limit-abbreviation-happened t))
(setf (pretty-stream-line-number stream) line-number)
(write-char #\newline target)
(setf (pretty-stream-buffer-start-column stream) 0)
(let* ((fill-ptr (pretty-stream-buffer-fill-pointer stream))
(block (first (pretty-stream-blocks stream)))
(prefix-len
(if literal-p
(logical-block-per-line-prefix-end block)
(logical-block-prefix-length block)))
(shift (- amount-to-consume prefix-len))
(new-fill-ptr (- fill-ptr shift))
(new-buffer buffer)
(buffer-length (length buffer)))
(when (> new-fill-ptr buffer-length)
(setf new-buffer
(make-string (max (* buffer-length 2)
(+ buffer-length
(floor (* (- new-fill-ptr buffer-length)
5)
4)))))
(setf (pretty-stream-buffer stream) new-buffer))
(replace new-buffer buffer
:start1 prefix-len :start2 amount-to-consume :end2 fill-ptr)
(replace new-buffer (pretty-stream-prefix stream)
:end1 prefix-len)
(setf (pretty-stream-buffer-fill-pointer stream) new-fill-ptr)
(incf (pretty-stream-buffer-offset stream) shift)
(unless literal-p
(setf (logical-block-section-column block) prefix-len)
(setf (logical-block-section-start-line block) line-number))))))
(defun output-partial-line (stream)
(let* ((fill-ptr (pretty-stream-buffer-fill-pointer stream))
(tail (pretty-stream-queue-tail stream))
(count
(if tail
(posn-index (queued-op-posn (car tail)) stream)
fill-ptr))
(new-fill-ptr (- fill-ptr count))
(buffer (pretty-stream-buffer stream)))
(when (zerop count)
(error "Output-partial-line called when nothing can be output."))
(output-buffer-with-annotations stream count)
(incf (pretty-stream-buffer-start-column stream) count)
(replace buffer buffer :end1 new-fill-ptr :start2 count :end2 fill-ptr)
(setf (pretty-stream-buffer-fill-pointer stream) new-fill-ptr)
(incf (pretty-stream-buffer-offset stream) count)))
(defun force-pretty-output (stream)
(maybe-output stream nil)
(expand-tabs stream nil)
(re-enqueue-annotations stream nil)
(output-buffer-with-annotations stream
(pretty-stream-buffer-fill-pointer stream)))
\ No newline at end of file
......@@ -227,7 +227,6 @@ If LOAD is true, load the fasl file."
'(swank-util swank-repl
swank-c-p-c swank-arglists swank-fuzzy
swank-fancy-inspector
swank-presentations swank-presentation-streams
#+(or asdf2 asdf3 sbcl ecl) swank-asdf
swank-package-fu
swank-hyperdoc
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment