How do I connect a clojure source file to a running clojure repl on Emacs? - emacs

I'm currently in the process of adding functionality to an existing J2EE webapp, in a Tomcat container, and I'm writing my additions using Clojure. My setup is simple: I just add calls to static methods generated by clojure, and code all the hard work from the clojure side. The build process consists in compiling clojure code (lein uberjar) and then compiling the java code with that jar on the classpath.
In the webapp init, I have a call to a generated class that fires up a swank server with a (swank/start-repl). I'd like to be able to connect my Aquamacs' slime to that server, and work interactively from there (up to a point, I won't try nothing that requires a java-side recompilation). But I have a situation that I don't quite understand. If I do a \M-x slime-connect, I get a REPL prompt (after being notified that there's no inferior lisp process, which I think it's ok, since the inferior lisp process is running outside emacs control). I can evaluate forms perfectly, and I can even inspect things like my.own.namespace/my-var. However, if I visit a file with an already compiled clojure code, I can't seem to make slime recognize it as its source. Consider a simple clojure file:
(ns my.namespace
(:gen-class
:name my.namespace
:methods [#^{:static true} [testFunc [] void]]))
(def *secret* "shhhh")
(defn -testFunc []
(println (str "our secret is: " secret)))
Assuming that this was compiled and included in the uberjar loaded by the webapp, I can eval/inspect my.namespace/*secret*. But If I try to eval inside the code buffer, Slime thinks I'm on the user namespace (which can even make sense!). But now I'm left with a single working option - I have to evaluate - one by one, all the forms in the file! \C-c \C-l (loading the source file) won't do nothing - apparently just returns nil and outputs nothing else. Compiling everything seems to do just that - it compiles, shows errors if it finds them, but won't change my namespace. And the strangest is the \C-~ (sync package and directory), which using Common Lisp it does just what I want, but here it freezes the clojure REPL for good.
There's always the option of switching to the REPL, typing (in-ns 'my.namespace), and then all works properly. But that simply isn't practical enough when the clojure files are growing in number (as the namespace of the code buffer won't change automatically!)
My question is, then, whether I'm lacking a basic command/configuration - or if there's an obvious reason for this behavior to happen as such.

I may be misunderstanding your problem, but can't you (while visiting this hypothetical buffer in emacs), hit C-c C-k to compile the buffer in your current Clojure instance (what Slime is connected to)?
Then, in the Slime buffer, switch to this namespace with a (in-ns 'my.namespace). Then you should have access to what you compiled in that namespace.

Switching namespaces automatically on compile has never been the default for swank-clojure, though it might be an optional slime feature that happened to work with Clojure. But C-c M-p to switch the repl to the current buffer's namespace has always worked for me, and I've never heard of anyone having trouble with it.
Are you running on the latest stable versions of clojure-mode and slime-repl? Do you have swank-clojure.el installed? (You shouldn't need it.) It sounds like this could be due to mismatched versions of the elisp libs. If that's not the problem it could be an Aquamacs bug; swank-clojure is designed to work with GNU Emacs. It could also be a bug in slime if you are running from trunk rather than the latest elpa release.

I've just found out that removing the culprit for this issue: slime-redirect-inferior-output, from slime-repl.el, was being called from a hook I had setup. It turns out that it doesn't play well without an inferior-lisp-process (read, a swank server started from within emacs).
So a quick workaround hack is just to remove the error form from that function, like this. Now the hook proceeds, and the namespaces are automatically calculated. As intended. Thank you for the suggestions, nevertheless - they led me to this solution!

Related

"illegal terminating character after a colon: #\" in portacle, though no colons in code

I've recently set up Portacle 1.3 for learning common lisp on Win 7. However, whenever I run my code I get the error, even if there is no code.
Running individual lines works fine, however. The error only shows when I run the whole file.
I tried putting some code in an EVAL function, but I believe that only accepts one argument at a time, so I couldn't run a whole program in it.
I've found a similar error in this stackoverflow page, but their code contains colons and that's where their error lies.
I think it might be an error in the code that runs mine, seeing as I get the error even if I compile with no code, however I know nothing.
The full error:
main.lisp:1:1:
read-error:
READ error during COMPILE-FILE:
illegal terminating character after a colon: #\
Line: 1, Column: 13, File-Position: 12
Stream: #<SB-INT:FORM-TRACKING-STREAM for "file [path to file]\\main.lisp" {1005F5F0D3}>
Compilation failed.
Portacle is a standalone Emacs packaged with everything needed for Common Lisp development and which uses SBCL as the Common Lisp implementation.
I believe what you do when you say 'compile the whole file' is call slime-compile-and-load-file which is bound to the key sequence C-c C-k by default. There are a lot of moving components here:
Emacs is the text editor here. It also takes care of launching all the necessary components for Common Lisp development.
Slime is one such component. It serves as interface between Emacs and your Common Lisp implementation (SBCL in this case, but supports any Lisp in theory). Basically it sends the code you wrote in Emacs to your Lisp for evaluation.
SBCL is the Common Lisp implementation. In this case it is a compiler. This is what evaluates the code it receives and spews out the answers to the user interface in Emacs, through Slime. It also 'lives', in the sense that you interact with it by modifying the state of the loaded Lisp image, keeping track of defined functions, global dynamic variables and much more. This is why you can have the REPL, and why you need Slime to interact with it.
So to debug your problem, I would try to:
Launch SBCL from the Windows shell and run a simple .lisp file to check that everything works. You can put for example (format t "~a" (lisp-implementation-type)) in a .lisp file and run it in SBCL from the shell by calling (load "...\\file.lisp"). It should return "SBCL".
Create a completely new file using Emacs (and not weird Windows programs that could mess up the files) (C-x C-f), and try to call the compile from there (C-c C-k).
And I believe you made the right choice of IDE. Portacle is arguably the simplest tool out there if you are a total beginner in Common Lisp and do not know Emacs configuration. The keybindings are a bit daunting though.

Emacs: dbus-related error when trying to switch to latex mode

since I began using dbus with Emacs some days ago (meaning I recompiled with dbus-support), when I open a latex-file or try to switch manually to latex-mode, I get
File mode specification error: (invalid-function dbus-ignore-errors)
and emacs stops there remaining in fundamental mode.
I use dbus for Zeitgeist-Support and that works fine and up to the recompilation, Auctex worked equally fine. I checked if the dbus-functions are available with the result: They show up in the help (including "dbus-ignore-errors") but they don't seem to be available for execute-extended-commad (M-x) meaning they don't show up in completion and cannot be executed. On the other hand they are available for lisp-eval.
I don't know if that's normal behavior for these functions, but anyway there seems to be some sort of a problem with the availability of the functions for auctex?
The situation does not change by disabling the zeitgeist-plugin.
Any suggestions?
Best regards
Matthias
The error invalid-function usually means that a piece of Emacs Lisp code was compiled before a certain macro was defined, and is now trying to call that macro as a function. To solve this, find the module in question and recompile it after making sure that the macro (dbus-ignore-errors in this case) is defined.
In the case of Auctex, this happens because tex.el contains the following:
;; Require dbus at compile time to prevent errors due to `dbus-ignore-errors'
;; not being defined.
(eval-when-compile (and (featurep 'dbusbind)
(require 'dbus nil :no-error)))
That is, it tries to load the dbus library, but ignores failures. If the Emacs under which Auctex is being compiled doesn't support dbus, dbus-ignore-errors will thus be compiled into a function call when compiling tex.el. That's no problem, because the dbus-ignore-errors call is protected by a featurep test.
If this byte-compiled file is then loaded into an Emacs instance that does support dbus, we suddenly reach the line in question, and try to call the macro as a function, which fails with invalid-function. That's why the file needs to be recompiled before being loaded into a dbus-enabled Emacs.
One way to solve this is to wrap the dbus-ignore-errors line into eval, changing this line:
(dbus-ignore-errors (dbus-get-unique-name :session))
to this:
(eval '(dbus-ignore-errors (dbus-get-unique-name :session)))
That would postpone the decision on how to evaluate that expression until runtime, when Emacs will know that dbus-ignore-errors is a macro.

How to clear the REPL in cider-mode?

I am not meaning cleaning up the text output of REPL; I mean cleaning up all evaluated results in REPL. During developing, repeatedly C-c C-q and C-c M-j is low efficiency.
UPDATE
There may be some bad debug behaviour of mine. I am not sure how other people develop progs with CIDER, but I really need the functionality mentioned above. I guess other developers also encounter same problems as mine.
For example, at the top of a clojure prog unit, I use declare to declare a function foo, which is used by another function bar, and foo is implemented after bar. Then, I C-c C-k, etc, and the prog goes well. Later, I removed the forward declaration of foo occasionally. What does happen? The prog still goes well. REALLY? Then, I commit my whole job and terminate the CIDER REPL session happily.
Disaster on morning: Symbol foo not found!
That's my story. So, nobody has ever encountered similar problems?
Try the (refresh) function in the clojure.tools.namespace.repl namespace:
The refresh function will scan all the directories on the classpath for Clojure source files, read their ns declarations, build a graph of their dependencies, and load them in dependency order.
https://github.com/clojure/tools.namespace#reloading-code-usage
It doesn't seem to remove the vars declared in the user namespace, which I've typed into the REPL, but it does:
...unload (remove) the namespaces that changed to clear out any old
definitions.
We generally add that plus a few other useful things to the user namespace, so it's loaded into the REPL on startup:
(ns user
(:require [clojure.tools.namespace.repl :refer [refresh]]
[clojure.repl :refer [doc source]]
[clojure.pprint :refer [pprint pp]]
[midje.repl :as midje]
[clojure.stacktrace :as st]))
To keep that code separate from your main and test sources, put that in a file at <project root>/dev/user.clj, then add the following to your lein project.clj file:
:profiles {:dev {:source-paths ["dev"]}}
(p.s. although it's not the question you want answered, for those seeing this answer and wanting to clear the text in the Cider REPL, it's C-c M-o (https://github.com/clojure-emacs/cider)
In EMACS when I works with Clojure in cider-mode, I use:
C-c M-o in the repl buffer
it is bound to cider-repl-clear-buffer
Like others have already pointed out, the 'proper' solution is to use Stuart Sierra's component library.
But since you're running in CIDER, you can use C-c C-x to run cider-refresh, which will reload your project and thereby recreate your initial state.
If you're dealing with a large number of things which have state which you want to clear to have a clean developing environment you might consider doing one of the following:
1.) Reassess your design and see how much of that state is actually necessary. In many situations you might be using atoms, refs, or other stateful items unnecessarily and if you adopt a more functional approach, you won't find yourself needing to clear up your development environment as often.
Presuming legitimate reasons for using state:
2.) You can wipe out a namespace and all of it's contents by using the clojure function remove-ns: e.g. for a namespace called user.fancy-namespace you can clean the NS out by running (remove-ns 'user.fancy-namespace') and then simply re-evaluating the namespace. This works well for cleaning up a single namespace, but if the stateful items you need cleaned are in other namespaces, it can get tedious to do this for every namespace involved.
3.) Stuart Sierra's component library was designed to manage components which involve state. Very useful for managing DB connections, memcache clients, etc, but will require a re-architecting of your project in order to make full use of it.
As mentioned by others, it is only necessary to clear the repl if you have variables which are holding state information. For non-state carrying components, just reloading the source buffer (re-evaluating it) is sufficient.
One very interesting way to manage a workflow which does have components that track state is Stuart Seirra's component framework. See http://youtu.be/13cmHf_kt-Q
Another approach is to write your code using defonce rather than def, which will allow you to reload your source code without redefining state variables.
If on the other hand, you want to do this to clean up defn or defmacro definitions you don't need i.e. clean out 'polution' from your repl, then to be honest, I wouldn't bother. If nothing is calling a defn or macro, it really doesn't matter.

Automatically load clojure libraries on cider connection

I constantly find myself doing multiple manual (require '[my.lib :as foo]) right after I start cider with M-x cider-jack-in in my clojure projects. I suspect there must be a hook to run some code on a successful connection. Is there? The alternative would be to put all requires in an external file and just (use 'that.namespace) but lazy as I am, I want to even skip that step if possible.
UPDATE:
Putting the forms in .lein/profiles.clj :injections is fine as long as one uses them exclusively in the Repl (as per lein repl). To make them available from the nrepl in emacs one must use the second solution named by arrdem below.
Here is some more comprehensive info.
Leiningen's :injections feature is the cannonical way to pull this one off. Once Lein boots a Clojure instance, the code in :injections gets evaluated allowing you as you say to populate the user namespace with libraries that you use all the time.
Another approach is to (ab)use the file user.clj by adding a :dev profile with a dev-only source path that "happens" to contain a user.clj with preloading code in it. This is done in Grimoire with the file dev/user.clj which serves to create some utility functions in the REPL.

Recompile doesn't correct typo in function call

I've been seeing this a lot lately and am not sure if it is an SBCL issue, an Emacs problem, a SLIME problem, or my own understanding of what it means to "compile" a lisp file.
I will have a function, say this:
(defun some-function (x) (call-this-funcshun))
I will compile and run this, and I'll get an error that my function call-this-funcshun is not defined. Then I realize that is because there is a typo. So change it:
(defun some-function (x) (call-this-function))
In Emacs, I recompile the entire file with Control-C Control-K (Emacs saves automatically before the compile as well). Emacs then reports Compilation finished. I move to the REPL. I try it again, type (some-function whatever) and I get the same error. I search through the small lisp file and see that call-this-funcshun is clearly nowhere in it. Yet I have an error that this function is not defined.
Is there some sort of caching that Emacs or SBCL is doing that causes this to hang around? It's driving me nuts. Worth noting that if I quit SLIME and then launch it again, the issue is resolved. Also worth noting that this does not affect all my code edits, just occasionally.
Maybe the file is not loaded for some reason.
I would set *load-verbose* to T and watch that LOAD actually gets called.
Setting *load-print* to T would then also cause the printing of information about definitions loaded.
I've seen two conditions that can lead to behavior that looks like what you saw:
When the symbol in the file is not the same as the symbol at the REPL. The symbol's name is only a shorthand for identifying the symbol, and the same shorthand can identify different symbols based on which package you use it in. There are some ways to be surprised about which symbol you are referring to, so it can be worth checking with SYMBOL-PACKAGE even when you are pretty sure that they are the same.
When the buffer isn't saved. I'm not sure how C-c C-k deals with this now (because I edited it to auto-save for me), but in general compiling and loading tools tend to work from the file not the buffer.