tags:

views:

131

answers:

1

I'm trying to embed a swank-clojure repl into my application for the purpose of connecting while the app is running to muck around with things. However, I'm having trouble figuring out how to access the enclosing environment after starting the repl.

Embedding the swank-clojure REPL is easy enough:

(ns mytest
  (:use [swank.swank :exclude [-main]])
  (:gen-class))

(defn -main [& args]
  (let [x 123]
    (swank.swank/start-repl)))

Run the program.. then over in emacs:

M-x slime-connect 

That works fine and I am connected. Now, what I hoped was that this would work:

(println x)
;; 123 (what I was hoping for)
;; Unable to resolve symbol: x in this context (cruel reality)

So that doesn't work as a way to pass the current environment to the embedded REPL.

Is there any way for the embedded REPL to interact with my running program?

If not, what reasons are there to embed a REPL?

If it makes any difference, I am trying to run this as a JAR.

This thread seems related, but I wasn't able to get anywhere from it:

http://stackoverflow.com/questions/2661025/embedding-swank-clojure-in-java-program

+4  A: 

let-bound locals are lexically scoped, thus swank.swank/start-repl won't be affected by a let form wrapped around the call to it. However, the running REPL will be able to require / use any Clojure namespaces on your application's classpath (or use in-ns to switch the REPL's namespace to one of those) and to import any Java classes on the classpath, allowing you to do a number of very useful things, such as redefining functions, examining and changing the contents of any Refs / Atoms / other things of interest held in Vars, calling functions / Java methods etc.

Note that you probably shouldn't (:use swank.swank) in your ns form; (:require swank.swank) instead. The difference is that the former pulls in all swank.swank's public Vars into your namespace, while the latter doesn't (use = require + refer, see (doc use) etc. for details). You seem to use namespace-qualified symbols to access Swank's Vars, so you might not even have to change the rest of your code, and require avoids cluttering up your namespace. Alternatively, (:use [swank.swank :only [start-repl]]); this pulls in just the start-repl Var, which you could then use directly, without the swank.swank/ bit.

Michał Marczyk
allclaws