Christophe Weblog Wiki Code Publications Music
don't print out "locals" from the global environment
[swankr.git] / swank.R
1 ### This program is free software; you can redistribute it and/or
2 ### modify it under the terms of the GNU General Public Licence as
3 ### published by the Free Software Foundation; either version 2 of the
4 ### Licence, or (at your option) any later version.
5 ###
6 ### This program is distributed in the hope that it will be useful,
7 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
8 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 ### GNU General Public Licence for more details.
10 ###
11 ### A copy of version 2 of the GNU General Public Licence is available
12 ### at <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>; the
13 ### latest version of the GNU General Public Licence is available at
14 ### <http://www.gnu.org/licenses/gpl.txt>.
15
16 ### KLUDGE: this assumes that we're being sourced with chdir=TRUE.
17 ### (If not, `swank:swank-require` will work under the circumstances
18 ### that it used to work anyway -- i.e. the working directory is the
19 ### swankr directory)
20 swankrPath <- getwd() 
21
22 swank <- function(port=4005) {
23   acceptConnections(port, FALSE)
24 }
25
26 startSwank <- function(portFile) {
27   acceptConnections(4005, portFile)
28 }
29
30 acceptConnections <- function(port, portFile) {
31   if(portFile != FALSE) {
32     f <- file(portFile, open="w+")
33     cat(port, file=f)
34     close(f)
35   }
36   s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
37   on.exit(close(s))
38   serve(s)
39 }
40
41 serve <- function(io) {
42   mainLoop(io)
43 }
44
45 mainLoop <- function(io) {
46   slimeConnection <- new.env()
47   slimeConnection$io <- io
48   while(TRUE) {
49     withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
50                           swankTopLevel=function(c) NULL),
51                  abort="return to SLIME's toplevel")
52   }
53 }
54
55 dispatch <- function(slimeConnection, event, sldbState=NULL) {
56   kind <- event[[1]]
57   if(kind == quote(`:emacs-rex`)) {
58     do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
59   }
60 }
61
62 sendToEmacs <- function(slimeConnection, obj) {
63   io <- slimeConnection$io
64   payload <- writeSexpToString(obj)
65   writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
66   writeChar(payload, io, eos=NULL)
67   flush(io)
68 }
69
70 callify <- function(form) {
71   ## we implement here the conversion from Lisp S-expression (or list)
72   ## expressions of code into our own, swankr, calling convention,
73   ## with slimeConnection and sldbState as first and second arguments.
74   ## as.call() gets us part of the way, but we need to walk the list
75   ## recursively to mimic CL:EVAL; we need to avoid converting R
76   ## special operators which we are punning (only `quote`, for now)
77   ## into this calling convention.
78   if(is.list(form)) {
79     if(form[[1]] == quote(quote)) {
80       as.call(form)
81     } else {
82       as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
83     }
84   } else {
85     form
86   }
87 }
88
89 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
90   ok <- FALSE
91   value <- NULL
92   conn <- textConnection(NULL, open="w")
93   condition <- NULL
94   tryCatch({
95     withCallingHandlers({
96       call <- callify(form)
97       capture.output(value <- eval(call), file=conn)
98       string <- paste(textConnectionValue(conn), sep="", collapse="\n")
99       if(nchar(string) > 0) {
100         sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
101         sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
102       }
103       close(conn)
104       ok <- TRUE
105     }, error=function(c) {
106       condition <<- c
107       string <- paste(textConnectionValue(conn), sep="", collapse="\n")
108       if(nchar(string) > 0) {
109         sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
110         sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
111       }
112       close(conn)
113       newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
114       withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
115     finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
116 }
117
118 makeSldbState <- function(condition, level, id) {
119   calls <- rev(sys.calls())[-1]
120   frames <- rev(sys.frames())[-1]
121   restarts <- rev(computeRestarts(condition))[-1]
122   ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
123   class(ret) <- c("sldbState", class(ret))
124   ret
125 }
126
127 sldbLoop <- function(slimeConnection, sldbState, id) {
128   tryCatch({
129     io <- slimeConnection$io
130     sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
131     sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
132     while(TRUE) {
133       dispatch(slimeConnection, readPacket(io), sldbState)
134     }
135   }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
136 }
137
138 readPacket <- function(io) {
139   socketSelect(list(io))
140   header <- readChunk(io, 6)
141   len <- strtoi(header, base=16)
142   payload <- readChunk(io, len)
143   readSexpFromString(payload)
144 }
145
146 readChunk <- function(io, len) {
147   buffer <- readChar(io, len)
148   if(nchar(buffer) != len) {
149     stop("short read in readChunk")
150   }
151   buffer
152 }
153
154 readSexpFromString <- function(string) {
155   pos <- 1
156   read <- function() {
157     skipWhitespace()
158     char <- substr(string, pos, pos)
159     switch(char,
160            "("=readList(),
161            "\""=readString(),
162            "'"=readQuote(),
163            {
164              if(pos > nchar(string))
165                stop("EOF during read")
166              obj <- readNumberOrSymbol()
167              if(obj == quote(`.`)) {
168                stop("Consing dot not implemented")
169              }
170              obj
171            })
172   }
173   skipWhitespace <- function() {
174     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
175       pos <<- pos + 1
176     }
177   }
178   readList <- function() {
179     ret <- list()
180     pos <<- pos + 1
181     while(TRUE) {
182       skipWhitespace()
183       char <- substr(string, pos, pos)
184       if(char == ")") {
185         pos <<- pos + 1
186         break
187       } else {
188         obj <- read()
189         if(length(obj) == 1 && obj == quote(`.`)) {
190           stop("Consing dot not implemented")
191         }
192         ret <- c(ret, list(obj))
193       }
194     }
195     ret
196   }
197   readString <- function() {
198     ret <- ""
199     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
200     while(TRUE) {
201       pos <<- pos + 1
202       char <- substr(string, pos, pos)
203       switch(char,
204              "\""={ pos <<- pos + 1; break },
205              "\\"={ pos <<- pos + 1
206                     char2 <- substr(string, pos, pos)
207                     switch(char2,
208                            "\""=addChar(char2),
209                            "\\"=addChar(char2),
210                            stop("Unrecognized escape character")) },
211              addChar(char))
212     }
213     ret
214   }
215   readNumberOrSymbol <- function() {
216     token <- readToken()
217     if(nchar(token)==0) {
218       stop("End of file reading token")
219     } else if(grepl("^[0-9]+$", token)) {
220       strtoi(token)
221     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
222       as.double(token)
223     } else {
224       name <- as.name(token)
225       if(name == quote(t)) {
226         TRUE
227       } else if(name == quote(nil)) {
228         FALSE
229       } else {
230         name
231       }
232     }
233   }
234   readToken <- function() {
235     token <- ""
236     while(TRUE) {
237       char <- substr(string, pos, pos)
238       if(char == "") {
239         break;
240       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
241         break;
242       } else {
243         token <- paste(token, char, sep="")
244         pos <<- pos + 1
245       }
246     }
247     token
248   }
249   read()
250 }
251
252 writeSexpToString <- function(obj) {
253   writeSexpToStringLoop <- function(obj) {
254     switch(typeof(obj),
255            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
256            "list"={ string <- paste(string, "(", sep="")
257                     max <- length(obj)
258                     if(max > 0) {
259                       for(i in 1:max) {
260                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
261                         if(i != max) {
262                           string <- paste(string, " ", sep="")
263                         }
264                       }
265                     }
266                     string <- paste(string, ")", sep="") },
267            "symbol"={ string <- paste(string, as.character(obj), sep="") },
268            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
269            "double"={ string <- paste(string, as.character(obj), sep="") },
270            "integer"={ string <- paste(string, as.character(obj), sep="") },
271            stop(paste("can't write object ", obj, sep="")))
272     string
273   }
274   string <- ""
275   writeSexpToStringLoop(obj)
276 }
277
278 prin1ToString <- function(val) {
279   paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
280         sep="", collapse="\n")
281 }
282
283 printToString <- function(val) {
284   paste(capture.output(print(val)), sep="", collapse="\n")
285 }
286
287 `swank:connection-info` <- function (slimeConnection, sldbState) {
288   list(quote(`:pid`), Sys.getpid(),
289        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
290        quote(`:lisp-implementation`), list(quote(`:type`), "R",
291                                            quote(`:name`), "R",
292                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
293 }
294
295 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
296   for(contrib in contribs) {
297     filename <- sprintf("%s/%s.R", swankrPath, as.character(contrib))
298     if(file.exists(filename)) {
299       source(filename)
300     }
301   }
302   list()
303 }
304
305 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
306   list("R", "R")
307 }
308
309 makeReplResult <- function(value) {
310   string <- printToString(value)
311   list(quote(`:write-string`), string,
312        quote(`:repl-result`))
313 }
314
315 makeReplResultFunction <- makeReplResult
316
317 sendReplResult <- function(slimeConnection, value) {
318   result <- makeReplResultFunction(value)
319   sendToEmacs(slimeConnection, result)
320 }
321
322 sendReplResultFunction <- sendReplResult
323
324 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
325   ## O how ugly
326   string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
327   for(expr in parse(text=string)) {
328     expr <- expr
329     ## O maybe this is even uglier
330     lookedup <- do.call("bquote", list(expr))
331     tmp <- withVisible(eval(lookedup, envir = globalenv()))
332     if(tmp$visible) {
333       sendReplResultFunction(slimeConnection, tmp$value)
334     }
335   }
336   list()
337 }
338
339 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
340   "No Arglist Information"
341 }
342
343 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
344   list()
345 }
346
347 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
348   condition <- simpleCondition("Throw to toplevel")
349   class(condition) <- c("swankTopLevel", class(condition))
350   signalCondition(condition)
351 }
352
353 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
354   calls <- sldbState$calls
355   if(is.null(to)) to <- length(calls)
356   from <- from+1
357   calls <- lapply(calls[from:to],
358                   { frameNumber <- from-1;
359                     function (x) {
360                       ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
361                       frameNumber <<- 1+frameNumber
362                       ret
363                     }
364                   })
365 }
366
367 computeRestartsForEmacs <- function (sldbState) {
368   lapply(sldbState$restarts,
369          function(x) {
370            ## this is all a little bit internalsy
371            restartName <- x[[1]][[1]]
372            description <- restartDescription(x)
373            list(restartName, if(is.null(description)) restartName else description)
374          })
375 }
376
377 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
378   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
379        computeRestartsForEmacs(sldbState),
380        `swank:backtrace`(slimeConnection, sldbState, from, to),
381        list(sldbState$id))
382 }
383
384 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
385   if(sldbState$level == level) {
386     invokeRestart(sldbState$restarts[[n+1]])
387   }
388 }
389
390 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
391   call <- sldbState$calls[[n+1]]
392   srcref <- attr(call, "srcref")
393   srcfile <- attr(srcref, "srcfile")
394   if(is.null(srcfile)) {
395     list(quote(`:error`), "no srcfile")
396   } else {
397     filename <- get("filename", srcfile)
398     ## KLUDGE: what this means is "is the srcfile filename
399     ## absolute?"
400     if(substr(filename, 1, 1) == "/") {
401       file <- filename
402     } else {
403       file <- sprintf("%s/%s", srcfile$wd, filename)
404     }
405     list(quote(`:location`),
406          list(quote(`:file`), file),
407          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
408          FALSE)
409   }
410 }
411
412 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
413   FALSE
414 }
415
416 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
417   frame <- sldbState$frames[[1+index]]
418   withRetryRestart("retry SLIME interactive evaluation request",
419                    value <- eval(parse(text=string), envir=frame))
420   printToString(value)
421 }
422
423 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
424   frame <- sldbState$frames[[1+index]]
425   objs <- ls(envir=frame)
426   if(identical(frame, globalenv())) {
427     objs <- c()
428   }
429   list(lapply(objs, function(name) { list(quote(`:name`), name,
430                                           quote(`:id`), 0,
431                                           quote(`:value`),
432                                           tryCatch({
433                                             printToString(eval(parse(text=name), envir=frame))
434                                           }, error=function(c) {
435                                             sprintf("error printing object")
436                                           }))}),
437        list())
438 }
439
440 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
441   literal2rx <- function(string) {
442     ## list of ERE metacharacters from ?regexp
443     gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
444   }
445   matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
446   nmatches <- length(matches)
447   if(nmatches == 0) {
448     list(list(), "")
449   } else {
450     longest <- matches[order(nchar(matches))][1]
451     while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
452       longest <- substr(longest, 1, nchar(longest)-1)
453     }
454     list(as.list(matches), longest)
455   }
456 }
457
458 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
459   lineOffset <- charOffset <- colOffset <- NULL
460   for(pos in position) {
461     switch(as.character(pos[[1]]),
462            `:position` = {charOffset <- pos[[2]]},
463            `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
464            warning("unknown content in pos", pos))
465   }
466   frob <- function(refs) {
467     lapply(refs,
468            function(x)
469            srcref(attr(x,"srcfile"),
470                   c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
471                     x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
472                     ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
473                     ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
474   }
475   transformSrcrefs <- function(s) {
476     srcrefs <- attr(s, "srcref")
477     attribs <- attributes(s)
478     new <- 
479       switch(mode(s),
480              "call"=as.call(lapply(s, transformSrcrefs)),
481              "expression"=as.expression(lapply(s, transformSrcrefs)),
482              s)
483     attributes(new) <- attribs
484     if(!is.null(attr(s, "srcref"))) {
485       attr(new, "srcref") <- frob(srcrefs)
486     }
487     new
488   }
489   withRestarts({
490     times <- system.time({
491       exprs <- parse(text=string, srcfile=srcfile(filename))
492       eval(transformSrcrefs(exprs), envir = globalenv()) })},
493                abort="abort compilation")
494   list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
495 }
496
497 withRetryRestart <- function(description, expr) {
498   call <- substitute(expr)
499   retry <- TRUE
500   while(retry) {
501     retry <- FALSE
502     withRestarts(eval.parent(call),
503                  retry=list(description=description,
504                    handler=function() retry <<- TRUE))
505   }
506 }
507
508 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
509   withRetryRestart("retry SLIME interactive evaluation request",
510                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
511   if(tmp$visible) {
512     prin1ToString(tmp$value)
513   } else {
514     "# invisible value"
515   }
516 }
517
518 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
519   withRetryRestart("retry SLIME interactive evaluation request",
520                    { output <-
521                        capture.output(tmp <- withVisible(eval(parse(text=string),
522                                                               envir=globalenv()))) })
523   output <- paste(output, sep="", collapse="\n")
524   if(tmp$visible) {
525     list(output, prin1ToString(tmp$value))
526   } else {
527     list(output, "# invisible value")
528   }
529 }
530
531 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
532   withRetryRestart("retry SLIME interactive evaluation request",
533                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
534   if(tmp$visible) {
535     prin1ToString(tmp$value)
536   } else {
537     "# invisible value"
538   }
539 }
540
541 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
542   if(exists(string, envir = globalenv())) {
543     thing <- get(string, envir = globalenv())
544     if(inherits(thing, "function")) {
545       body <- body(thing)
546       srcref <- attr(body, "srcref")
547       srcfile <- attr(body, "srcfile")
548       if(is.null(srcfile)) {
549         list()
550       } else {
551         filename <- get("filename", srcfile)
552         ## KLUDGE: what this means is "is the srcfile filename
553         ## absolute?"
554         if(substr(filename, 1, 1) == "/") {
555           file <- filename
556         } else {
557           file <- sprintf("%s/%s", srcfile$wd, filename)
558         }
559         list(list(sprintf("function %s", string),
560                   list(quote(`:location`),
561                        list(quote(`:file`), file),
562                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
563                        list())))
564       }
565     } else {
566       list()
567     }
568   } else {
569     list()
570   }
571 }
572
573 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
574   paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
575         collapse="\n", sep="")
576 }
577
578 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
579   eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
580   TRUE
581 }
582
583 resetInspector <- function(slimeConnection) {
584   assign("istate", list(), envir=slimeConnection)
585   assign("inspectorHistory", NULL, envir=slimeConnection)
586 }
587
588 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
589   withRetryRestart("retry SLIME inspection request",
590                    { resetInspector(slimeConnection)
591                      value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
592                    })
593   value
594 }
595
596 inspectObject <- function(slimeConnection, object) {
597   previous <- slimeConnection$istate
598   slimeConnection$istate <- new.env()
599   slimeConnection$istate$object <- object
600   slimeConnection$istate$previous <- previous
601   slimeConnection$istate$content <- emacsInspect(object)
602   if(!(object %in% slimeConnection$inspectorHistory)) {
603     slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
604   }
605   if(!is.null(slimeConnection$istate$previous)) {
606     slimeConnection$istate$previous$`next` <- slimeConnection$istate
607   }
608   istateToElisp(slimeConnection$istate)
609 }
610
611 valuePart <- function(istate, object, string) {
612   list(quote(`:value`),
613        if(is.null(string)) printToString(object) else string,
614        assignIndexInParts(object, istate))
615 }
616
617 preparePart <- function(istate, part) {
618   if(is.character(part)) {
619     list(part)
620   } else {
621     switch(as.character(part[[1]]),
622            `:newline` = list("\n"),
623            `:value` = valuePart(istate, part[[2]], part[[3]]),
624            `:line` = list(printToString(part[[2]]), ": ",
625              valuePart(istate, part[[3]], NULL), "\n"))
626   }
627 }
628
629 prepareRange <- function(istate, start, end) {
630   range <- istate$content[start+1:min(end+1, length(istate$content))]
631   ps <- NULL
632   for(part in range) {
633     ps <- c(ps, preparePart(istate, part))
634   }
635   list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
636        start, end)
637 }
638
639 assignIndexInParts <- function(object, istate) {
640   ret <- 1+length(istate$parts)
641   istate$parts <- c(istate$parts, list(object))
642   ret
643 }
644
645 istateToElisp <- function(istate) {
646   list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
647        quote(`:id`), assignIndexInParts(istate$object, istate),
648        quote(`:content`), prepareRange(istate, 0, 500))
649 }
650
651 emacsInspect <- function(object) {
652   UseMethod("emacsInspect")
653 }
654
655 emacsInspect.default <- function(thing) {
656   c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
657 }
658
659 emacsInspect.list <- function(list) {
660   c(list("a list", list(quote(`:newline`))),
661     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
662            names(list), list))
663 }
664
665 emacsInspect.numeric <- function(numeric) {
666   c(list("a numeric", list(quote(`:newline`))),
667     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
668            (1:length(numeric)), numeric))
669 }
670
671 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
672   resetInspector(slimeConnection)
673   FALSE
674 }
675
676 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
677   slimeConnection$istate$parts[[index]]
678 }
679
680 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
681   object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
682   inspectObject(slimeConnection, object)
683 }
684
685 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
686   if(!is.null(slimeConnection$istate$previous)) {
687     slimeConnection$istate <- slimeConnection$istate$previous
688     istateToElisp(slimeConnection$istate)
689   } else {
690     FALSE
691   }
692 }
693
694 `swank:inspector-next` <- function(slimeConnection, sldbState) {
695   if(!is.null(slimeConnection$istate$`next`)) {
696     slimeConnection$istate <- slimeConnection$istate$`next`
697     istateToElisp(slimeConnection$istate)
698   } else {
699     FALSE
700   }
701 }
702
703 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
704   expr <- parse(text=string)[[1]]
705   object <- slimeConnection$istate$object
706   if(inherits(object, "list")|inherits(object, "environment")) {
707     substituted <- substituteDirect(expr, object)
708     eval(substituted, envir=globalenv())
709   } else {
710     eval(expr, envir=globalenv())
711   }
712 }
713
714 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
715   resetInspector(slimeConnection)
716   inspectObject(slimeConnection, sldbState$condition)
717 }
718
719 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
720   resetInspector(slimeConnection)
721   frame <- sldbState$frames[[1+frame]]
722   name <- ls(envir=frame)[[1+var]]
723   object <- get(name, envir=frame)
724   inspectObject(slimeConnection, object)
725 }
726
727 `swank:default-directory` <- function(slimeConnection, sldbState) {
728   getwd()
729 }
730
731 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
732   setwd(directory)
733   `swank:default-directory`(slimeConnection, sldbState)
734 }
735
736 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
737   source(filename, local=FALSE, keep.source=TRUE)
738   TRUE
739 }
740
741 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
742   times <- system.time(parse(filename, srcfile=srcfile(filename)))
743   if(loadp) {
744     ## KLUDGE: inelegant, but works.  It might be more in the spirit
745     ## of things to keep the result of the parse above around to
746     ## evaluate.
747     `swank:load-file`(slimeConnection, sldbState, filename)
748   }
749   list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
750 }
751
752 `swank:quit-lisp` <- function(slimeConnection, sldbState) {
753   quit()
754 }