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