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