Christophe Weblog Wiki Code Publications Music
ce757b3995574feaacd94ed83dbdd5fbe03ea27b
[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   list(lapply(objs, function(name) { list(quote(`:name`), name,
427                                           quote(`:id`), 0,
428                                           quote(`:value`),
429                                           tryCatch({
430                                             printToString(eval(parse(text=name), envir=frame))
431                                           }, error=function(c) {
432                                             sprintf("error printing object")
433                                           }))}),
434        list())
435 }
436
437 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
438   literal2rx <- function(string) {
439     ## list of ERE metacharacters from ?regexp
440     gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
441   }
442   matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
443   nmatches <- length(matches)
444   if(nmatches == 0) {
445     list(list(), "")
446   } else {
447     longest <- matches[order(nchar(matches))][1]
448     while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
449       longest <- substr(longest, 1, nchar(longest)-1)
450     }
451     list(as.list(matches), longest)
452   }
453 }
454
455 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
456   lineOffset <- charOffset <- colOffset <- NULL
457   for(pos in position) {
458     switch(as.character(pos[[1]]),
459            `:position` = {charOffset <- pos[[2]]},
460            `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
461            warning("unknown content in pos", pos))
462   }
463   frob <- function(refs) {
464     lapply(refs,
465            function(x)
466            srcref(attr(x,"srcfile"),
467                   c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
468                     x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
469                     ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
470                     ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
471   }
472   transformSrcrefs <- function(s) {
473     srcrefs <- attr(s, "srcref")
474     attribs <- attributes(s)
475     new <- 
476       switch(mode(s),
477              "call"=as.call(lapply(s, transformSrcrefs)),
478              "expression"=as.expression(lapply(s, transformSrcrefs)),
479              s)
480     attributes(new) <- attribs
481     if(!is.null(attr(s, "srcref"))) {
482       attr(new, "srcref") <- frob(srcrefs)
483     }
484     new
485   }
486   withRestarts({
487     times <- system.time({
488       exprs <- parse(text=string, srcfile=srcfile(filename))
489       eval(transformSrcrefs(exprs), envir = globalenv()) })},
490                abort="abort compilation")
491   list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
492 }
493
494 withRetryRestart <- function(description, expr) {
495   call <- substitute(expr)
496   retry <- TRUE
497   while(retry) {
498     retry <- FALSE
499     withRestarts(eval.parent(call),
500                  retry=list(description=description,
501                    handler=function() retry <<- TRUE))
502   }
503 }
504
505 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
506   withRetryRestart("retry SLIME interactive evaluation request",
507                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
508   if(tmp$visible) {
509     prin1ToString(tmp$value)
510   } else {
511     "# invisible value"
512   }
513 }
514
515 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
516   withRetryRestart("retry SLIME interactive evaluation request",
517                    { output <-
518                        capture.output(tmp <- withVisible(eval(parse(text=string),
519                                                               envir=globalenv()))) })
520   output <- paste(output, sep="", collapse="\n")
521   if(tmp$visible) {
522     list(output, prin1ToString(tmp$value))
523   } else {
524     list(output, "# invisible value")
525   }
526 }
527
528 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
529   withRetryRestart("retry SLIME interactive evaluation request",
530                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
531   if(tmp$visible) {
532     prin1ToString(tmp$value)
533   } else {
534     "# invisible value"
535   }
536 }
537
538 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
539   if(exists(string, envir = globalenv())) {
540     thing <- get(string, envir = globalenv())
541     if(inherits(thing, "function")) {
542       body <- body(thing)
543       srcref <- attr(body, "srcref")
544       srcfile <- attr(body, "srcfile")
545       if(is.null(srcfile)) {
546         list()
547       } else {
548         filename <- get("filename", srcfile)
549         ## KLUDGE: what this means is "is the srcfile filename
550         ## absolute?"
551         if(substr(filename, 1, 1) == "/") {
552           file <- filename
553         } else {
554           file <- sprintf("%s/%s", srcfile$wd, filename)
555         }
556         list(list(sprintf("function %s", string),
557                   list(quote(`:location`),
558                        list(quote(`:file`), file),
559                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
560                        list())))
561       }
562     } else {
563       list()
564     }
565   } else {
566     list()
567   }
568 }
569
570 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
571   paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
572         collapse="\n", sep="")
573 }
574
575 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
576   eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
577   TRUE
578 }
579
580 resetInspector <- function(slimeConnection) {
581   assign("istate", list(), envir=slimeConnection)
582   assign("inspectorHistory", NULL, envir=slimeConnection)
583 }
584
585 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
586   withRetryRestart("retry SLIME inspection request",
587                    { resetInspector(slimeConnection)
588                      value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
589                    })
590   value
591 }
592
593 inspectObject <- function(slimeConnection, object) {
594   previous <- slimeConnection$istate
595   slimeConnection$istate <- new.env()
596   slimeConnection$istate$object <- object
597   slimeConnection$istate$previous <- previous
598   slimeConnection$istate$content <- emacsInspect(object)
599   if(!(object %in% slimeConnection$inspectorHistory)) {
600     slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
601   }
602   if(!is.null(slimeConnection$istate$previous)) {
603     slimeConnection$istate$previous$`next` <- slimeConnection$istate
604   }
605   istateToElisp(slimeConnection$istate)
606 }
607
608 valuePart <- function(istate, object, string) {
609   list(quote(`:value`),
610        if(is.null(string)) printToString(object) else string,
611        assignIndexInParts(object, istate))
612 }
613
614 preparePart <- function(istate, part) {
615   if(is.character(part)) {
616     list(part)
617   } else {
618     switch(as.character(part[[1]]),
619            `:newline` = list("\n"),
620            `:value` = valuePart(istate, part[[2]], part[[3]]),
621            `:line` = list(printToString(part[[2]]), ": ",
622              valuePart(istate, part[[3]], NULL), "\n"))
623   }
624 }
625
626 prepareRange <- function(istate, start, end) {
627   range <- istate$content[start+1:min(end+1, length(istate$content))]
628   ps <- NULL
629   for(part in range) {
630     ps <- c(ps, preparePart(istate, part))
631   }
632   list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
633        start, end)
634 }
635
636 assignIndexInParts <- function(object, istate) {
637   ret <- 1+length(istate$parts)
638   istate$parts <- c(istate$parts, list(object))
639   ret
640 }
641
642 istateToElisp <- function(istate) {
643   list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
644        quote(`:id`), assignIndexInParts(istate$object, istate),
645        quote(`:content`), prepareRange(istate, 0, 500))
646 }
647
648 emacsInspect <- function(object) {
649   UseMethod("emacsInspect")
650 }
651
652 emacsInspect.default <- function(thing) {
653   c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
654 }
655
656 emacsInspect.list <- function(list) {
657   c(list("a list", list(quote(`:newline`))),
658     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
659            names(list), list))
660 }
661
662 emacsInspect.numeric <- function(numeric) {
663   c(list("a numeric", list(quote(`:newline`))),
664     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
665            (1:length(numeric)), numeric))
666 }
667
668 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
669   resetInspector(slimeConnection)
670   FALSE
671 }
672
673 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
674   slimeConnection$istate$parts[[index]]
675 }
676
677 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
678   object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
679   inspectObject(slimeConnection, object)
680 }
681
682 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
683   if(!is.null(slimeConnection$istate$previous)) {
684     slimeConnection$istate <- slimeConnection$istate$previous
685     istateToElisp(slimeConnection$istate)
686   } else {
687     FALSE
688   }
689 }
690
691 `swank:inspector-next` <- function(slimeConnection, sldbState) {
692   if(!is.null(slimeConnection$istate$`next`)) {
693     slimeConnection$istate <- slimeConnection$istate$`next`
694     istateToElisp(slimeConnection$istate)
695   } else {
696     FALSE
697   }
698 }
699
700 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
701   expr <- parse(text=string)[[1]]
702   object <- slimeConnection$istate$object
703   if(inherits(object, "list")|inherits(object, "environment")) {
704     substituted <- substituteDirect(expr, object)
705     eval(substituted, envir=globalenv())
706   } else {
707     eval(expr, envir=globalenv())
708   }
709 }
710
711 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
712   resetInspector(slimeConnection)
713   inspectObject(slimeConnection, sldbState$condition)
714 }
715
716 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
717   resetInspector(slimeConnection)
718   frame <- sldbState$frames[[1+frame]]
719   name <- ls(envir=frame)[[1+var]]
720   object <- get(name, envir=frame)
721   inspectObject(slimeConnection, object)
722 }
723
724 `swank:default-directory` <- function(slimeConnection, sldbState) {
725   getwd()
726 }
727
728 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
729   setwd(directory)
730   `swank:default-directory`(slimeConnection, sldbState)
731 }
732
733 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
734   source(filename, local=FALSE, keep.source=TRUE)
735   TRUE
736 }
737
738 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
739   times <- system.time(parse(filename, srcfile=srcfile(filename)))
740   if(loadp) {
741     ## KLUDGE: inelegant, but works.  It might be more in the spirit
742     ## of things to keep the result of the parse above around to
743     ## evaluate.
744     `swank:load-file`(slimeConnection, sldbState, filename)
745   }
746   list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
747 }
748
749 `swank:quit-lisp` <- function(slimeConnection, sldbState) {
750   quit()
751 }