Automatically load clojure libraries on cider connection - emacs

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.

Related

How and where to set the default load location for sbcl / slime / emacs on Ubuntu 18

I have emacs / sbcl / slime working.
I'm going through a tutorial and hit the following example:
CL-USER> (load "hello.lisp")
; Loading /home/peter/my-lisp-programs/hello.lisp
The author doesn't specify how or where he set things up to default the load location to his example.
I've tried creating the EMACSLOADPATH environment variable and have tried a setq for load-path all with no positive results.
If I load a .lisp file using the entire path as in /home/bill/lisp/hello.lisp, it load and I can run it. Id like to know how and where to set the default to "~/lisp" so I can avoid an absolute path reference.
Before the answer, EMACSLOADPATH (or load-path) isn't related to common-lisp or sbcl (which is a common-lisp implementation). It is an emacs related variable. The root of the confusion is understandable, as emacs is a tool build on its own variant of lisp, elisp, and you write elisp code to extend or configure emacs. Emacs tool has its own elisp engine that runs those elips commands. And then you start using emacs as an editor to write common-lisp code, using plugins like slime to make it easier to interact with sbcl interpreter (or any other slime compatible common-lisp interpreter, for that matter).
For the default load location of common-lisp, load function of sbcl uses *default-pathname-defaults* to form the pathname from the argument, and it is generally set to the current directory (by slime at least - check swank:set-default-directory).
However, if you want an approach similar to python's import, where the function uses a list of directories to search for, I believe there are two options to start with.
Use quicklisp or asdf, as they are equivalent to python-import, but that probably means you define a 'system' (python: 'module') and use asdf:load-system. Here is an answer for this solution: example of using external libs in common-lisp
Write a load function yourself, and search for a predefined list of directories for the file name, and form an absolute path then call cl:load with the absolute path you decide.

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.

How do I connect a clojure source file to a running clojure repl on 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!

Emacs recursive project search

I am switching to Emacs from TextMate. One feature of TextMate that I would really like to have in Emacs is the "Find in Project" search box that uses fuzzy matching. Emacs sort of has this with ido, but ido does not search recursively through child directories. It searches only within one directory.
Is there a way to give ido a root directory and to search everything under it?
Update:
The questions below pertain to find-file-in-project.el from MichaƂ Marczyk's answer.
If anything in this message sounds obvious it's because I have used Emacs for less than one week. :-)
As I understand it, project-local-variables lets me define things in a .emacs-project file that I keep in my project root.
How do I point find-file-in-project to my project root?
I am not familiar with regex syntax in Emacs Lisp. The default value for ffip-regexp is:
".*\\.\\(rb\\|js\\|css\\|yml\\|yaml\\|rhtml\\|erb\\|html\\|el\\)"
I presume that I can just switch the extensions to the ones appropriate for my project.
Could you explain the ffip-find-options? From the file:
(defvar ffip-find-options
""
"Extra options to pass to `find' when using find-file-in-project.
Use this to exclude portions of your project: \"-not -regex \\".vendor.\\"\"")
What does this mean exactly and how do I use it to exclude files/directories?
Could you share an example .emacs-project file?
I use M-x rgrep for this. It automatically skips a lot of things you don't want, like .svn directories.
(Updated primarily in order to include actual setup instructions for use with the below mentioned find-file-in-project.el from the RINARI distribution. Original answer left intact; the new bits come after the second horizontal rule.)
Have a look at the TextMate page of the EmacsWiki. The most promising thing they mention is probably this Emacs Lisp script, which provides recursive search under a "project directory" guided by some variables. That file begins with an extensive comments section describing how to use it.
What makes it particularly promising is the following bit:
;; If `ido-mode' is enabled, the menu will use `ido-completing-read'
;; instead of `completing-read'.
Note I haven't used it myself... Though I may very well give it a try now that I've found it! :-)
HTH.
(BTW, that script is part of -- to quote the description from GitHub -- "Rinari Is Not A Rails IDE (it is an Emacs minor mode for Rails)". If you're doing any Rails development, you might want to check out the whole thing.)
Before proceeding any further, configure ido.el. Seriously, it's a must-have on its own and it will improve your experience with find-file-in-project. See this screencast by Stuart Halloway (which I've already mentioned in a comment on this answer) to learn why you need to use it. Also, Stu demonstrates how flexible ido is by emulating TextMate's project-scoped file-finding facility in his own way; if his function suits your needs, read no further.
Ok, so here's how to set up RINARI's find-file-in-project.el:
Obtain find-file-in-project.el and project-local-variables.el from the RINARI distribution and put someplace where Emacs can find them (which means in one of the directories in the load-path variable; you can use (add-to-list 'load-path "/path/to/some/directory") to add new directories to it).
Add (require 'find-file-in-project) to your .emacs file. Also add the following to have the C-x C-M-f sequence bring up the find-file-in-project prompt: (global-set-key (kbd "C-x C-M-f") 'find-file-in-project).
Create a file called .emacs-project in your projects root directory. At a minimum it should contain something like this: (setl ffip-regexp ".*\\.\\(clj\\|py\\)$"). This will make it so that only files whose names and in clj or py will be searched for; please adjust the regex to match your needs. (Note that this regular expression will be passed to the Unix find utility and should use find's preferred regular expression syntax. You still have to double every backslash in regexes as is usual in Emacs; whether you also have to put backslashes before parens / pipes (|) if you want to use their 'magic' regex meaning depends on your find's expectations. The example given above works for me on an Ubuntu box. Look up additional info on regexes in case of doubt.) (Note: this paragraph has been revised in the last edit to fix some confusion w.r.t. regular expression syntax.)
C-x C-M-f away.
There's a number of possible customisations; in particular, you can use (setl ffip-find-options "...") to pass additional options to the Unix find command, which is what find-file-in-project.el calls out to under the hood.
If things appear not to work, please check and double check your spelling -- I did something like (setl ffip-regex ...) once (note the lack of the final 'p' in the variable name) and were initially quite puzzled to discover that no files were being found.
Surprised nobody mentioned https://github.com/defunkt/textmate.el (now gotta make it work on Windows...)
eproject has eproject-grep, which does exactly what you want.
With the right project definition, it will only search project files; it will ignore version control, build artifacts, generated files, whatever. The only downside is that it requires a grep command on your system; this dependency will be eliminated soon.
You can get the effect you want by using GNU Global or IDUtils. They are not Emacs specific, but they has Emacs scripts that integrate that effect. (I don't know too much about them myself.)
You could also opt to use CEDET and the EDE project system. EDE is probably a bit heavy weight, but it has a way to just mark the top of a project. If you also keep GNU Global or IDUtils index files with your project, EDE can use it to find a file by name anywhere, or you can use `semantic-symref' to find references to symbols in your source files. CEDET is at http://cedet.sf.net
For pure, unadulterated speed, I highly recommend a combination of the command-line tool The Silver Searcher (a.k.a. 'ag') with ag.el. The ag-project interactive function will make an educated guess of your project root if you are using git, hg or svn and search the entire project.
FileCache may also be an option. However you would need to add your project directory manually with file-cache-add-directory-recursively.
See these links for info about how Icicles can help here:
find files anywhere, matching any parts of their name (including directory parts)
projects: create, organize, manage, search them
Icicles completion matching can be substring, regexp, fuzzy (various kinds), or combinations of these. You can also combine simple patterns, intersecting the matches or complementing (subtracting) a subset of them

Company mode (Emacs plugin) back-end could not be initialized?

Every time I initiate company-mode with M-x company-mode this message shows up:
Company back-end 'company-semantic' could not be initialized
Company back-end 'company-ropemacs' could not be initialized
Company back-end 'company-pysmell' could not be initialized
The completion works but I wonder whats the meaning of that message and how to fix it.
EDIT: I moved company-semantic.el company-ropemacs.el company-pysmell.el to ~.emacs.d\plugins\company-0.4.3\unused-backends but I'm still getting that error.
Instead of changing your company-mode install directory. Just define company-backends in your .emacs file. E.g.
(setq company-backends '(company-elisp
company-ropemacs
company-gtags
company-dabbrev-code
company-keywords
company-files
company-dabbrev))
Excluding the backends you do not want to support from the list.
semantic, ropemacs and pysmell are all emacs extensions. Do you have them installed?
If you don't intend to use them, a quick workaround would be to remove or move that files that define those back-ends, which would prevent company mode from trying to load them.
cd /location/of/company
mkdir unused-backends
mv company-semantic.* company-ropemacs.* company-pysmell.* unused-backends/
As long as you do not add unused-backends to your load-path, this will fix the problem.
If you want to use those backends (semantic is a parser for better context-appropriate emacs actions based on language, pysmell and ropemacs are both for usage with python), then installing them should fix this problem.