Evaluating Elisp in emacs - emacs

I am an hour new into programming in Emacs lisp. I have a little experience with scheme so I understand the big picture of lisps in general. However, I have only used the "pure functional" subset of scheme and do not know how to do practical tasks.
Write now, I know that C-x C-e will evaluate the code enclosed by the parentheses' by the current cursor position.
I wish to loop from i = 1 to 10 and print the values of i out. How is this done? I tried the following:
(defvar i 1)
(while (< i 11)
(print "i: " i)
(setq i (+ i 1)))
Emacs tells me: invalid function 0.
How do I do this correctly?
Why is emacs telling me invalid function 0
Feel free to give me tips about how to use the scratch buffer (all I know is C-x C-e evaluates) in emacs. Thanks for all the help!
EDIT1: Could someone tell me how to print out sequential values of i using a while loop?
EDIT2: When I evaluate the code, it opens up another tiny buffer showing each value of i one at a time. However, it is not a large buffer and only shows values of i from 13 to 19. When I try to get into that buffer, it closes immediately. How do I "scroll" through that tiny buffer? Note that I use emacs 24.3 through the terminal
EDIT3: I figured out that the tiny buffer is the Messages buffer. Is there a better way to view the output of my elisp code? The Messages buffer is full of other junk from evaluating things in emacs.

First and foremost, enable "Enter debugger on error" from the Options menu now and add (setq debug-on-error t) or (custom-set-variables '(debug-on-error t)) to your ~/.emacs.el.
Then you will get a *Backtrace* buffer on C-x C-e:
Debugger entered--Lisp error: (invalid-function 1)
1(10)
print("i: " 1)
(while (< i 11) (print "i: " i) (setq i (+ i 1)))
eval((while (< i 11) (print "i: " i) (setq i (+ i 1))) nil)
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp nil nil)
command-execute(eval-last-sexp)
which shows that the error comes from print.
C-h f print RET will tell you why, but the upshot is that you want to use insert instead of print here.

Just as an added note, since you mentioned knowing some scheme -- if you like the interactive REPL that you can use in typical scheme environment, you might like ielm -- I think it probably stands for Interactive Emacs Lisp mode. Not sure. Anyway, M-x ielm RET will open up an emacs lisp REPL. Sometimes it is actually useful -- for example, when you want to inspect the content of a variable with a lot of data in it, ielm will print the whole thing out. Ielm is built in to my Emacs. Not sure when it was added to the standard distribution, but the earliest copyright in the source says 1994, so it is probably in your Emacs.

You can evaluate Emacs-Lisp sexps in *scratch* or in any other buffer in the same mode or (my preference) in mode emacs-lisp-mode.
In *scratch* you need only hit C-j (newline) after a sexp to evaluate it. In an emacs-lisp-mode buffer you can, as you said, use C-x C-e after a sexp. Or you can use M-x evaluate-region after selecting one or more sexps. As always, C-h m in any mode tells you about it, and usually lists important key bindings.
You can also check a global variable value using C-h v SOME-VAR. And you can evaluate any sexp on the fly from the minibuffer, using M-:. For example: M-: (setq foo (+ 42 (length bar)))
Wrt the debugger:
As #sds mentioned, debug-on-error puts you in the debugger when an error is raised. You can also set debug-on-quit and then enter the debugger using C-g to quit (e.g., during a loop).
If you know the function you want to debug, you can use M-x debug-on-entry.
Step through the debugger using d, or skip to the end of a step using c. Use q to quit the debugger.
You can also insert calls to function debug in source code, as debugger entry points: (debug).
The backtrace in the debugger is always more informative if you load the relevant source file e.g., foo.el, instead of the byte-compiled file, e.g., foo.elc. So before you use M-x debug-on-entry use C-h f to find out which file the function is defined in, and then load that file using M-x load-file /path/to/the/file.el.
There is also another debugger, besides debug -- look for edebug in the Elisp manual. Some people prefer edebug; I prefer debug.

Related

How can I load changes of .el file at startup in Emacs?

I have installed Emacs under Windows 7 and want to use it in my everyday work. Unfortunately Emacs world and other text editors world are completely different and I am getting stuck on every third sequence of keys pressed on keyboard - it's doing something that I don't expect it would do.
I want to make a panic command - when I press ESC ESC ESC it stops doing everything, quitting from minibuffer, stops entering command, unhighlight regexps, etc. It already does what I want, except it killing buffers, the layout of my workspace. So I modified keyboard-escape-quit function in simple.el file (found it by C-h k ESC ESC ESC)
(defun keyboard-escape-quit ()
"Exit the current \"mode\" (in a generalized sense of the word).
This command can exit an interactive command such as `query-replace',
can clear out a prefix argument or a region,
can get out of the minibuffer or other recursive edit,
cancel the use of the current buffer (for special-purpose buffers),
or go back to just one window (by deleting all but the selected window)."
(interactive)
; Stop highlighting regexp
(unhighlight-regexp)
(cond ((eq last-command 'mode-exited) nil)
((region-active-p)
(deactivate-mark))
((> (minibuffer-depth) 0)
(abort-recursive-edit))
(current-prefix-arg
nil)
((> (recursion-depth) 0)
(exit-recursive-edit))
(buffer-quit-function
(funcall buffer-quit-function))
;((not (one-window-p t))
; (delete-other-windows))
((string-match "^ \\*" (buffer-name (current-buffer)))
(bury-buffer))))
I have byte-compiled and loaded this file and it works ok. But I can't figure out why it is not loading at startup.
You cannot modify some special built-in libraries, including simple.el. Emacs never actually loads these special libraries from their source or byte code files. Their byte code is directly included in the Emacs executable at build time, by a process called “dumping”. Emacs loads these libraries from its own binary.
Generally, should not modify any built-in libraries anyway. Your risk breakage, and your customizations are lost when you update Emacs.
Instead, do what you are supposed to do: Add custom functions to your init.el.
Hence, instead of modifying the built-in keyboard-escape-quit, create your own function, e.g. my-emergency-quit, in your init.el, and bind it to a global key, e.g. C-c q, with
(global-set-key (kbd "C-c q") #'my-emergency-quit)
Some final words of advice: I do not think that such a panic command does any good. The first rule of Emacs is: Don't panic. If you are stuck, don't try to quit and kill everything. Rather, try to find out why you are stuck, and how to get “un-stuck” by normal means. You'll learn Emacs better this way, imho.

How to make emacs switch to *scheme* by default when eval / load from the file?

The problem:
I'm in scheme-mode (simple quack)
scheme is already running
eval expression
it sends the expression to scheme buffer
but! doesn't bring that buffer up in 2nd window = no immediate feedback
and I have to manually switch second buffer to scheme which is annoying
Some (more recent) modes like fsharp-mode or tuareg do that automatically. Tried to read quack.el, but didn't find convenient separate function like "pop scheme". It's tangled within run-scheme which also changes focus. Settings also don't help.
I want to stay in my rkt/scm file and see repl buffer pop up if not already popped. Like this simple build logic in sublime-text but with persistent repl.
Maybe I should try geiser, but quack is ok for now. Just missing few obvious conveniences.
Just rungeiser. It's in MELPA now, so it's a quick install.
You can also try lispy (which uses geiser) for in-place scheme eval.
e will eval current expression and display the result in the minibuffer.
E will eval current expression and insert the result in current buffer.
u is bound to undo, so you can either e or Eu if you prefer.
I ended up writing this:
(setq scheme-program-name "guile")
(defun run-scheme-2.0 ()
"Loads your chosen Scheme implementation for interactive development,
and displays that buffer below your main editing buffer, and makes sure that
your cursor will be on your code."
(interactive)
(if (not (get-buffer "*scheme*"))
(progn
(setq starting-buffer (buffer-name))
(run-scheme scheme-program-name)
(split-window-below)
(other-window 1)
(shrink-window-if-larger-than-buffer)
(other-window 1)
(switch-to-buffer starting-buffer))))
(add-hook 'scheme-mode-hook 'run-scheme-2.0)

*scratch* buffer using SLIME

I realize that SLIME is the Superior Lisp Interaction Mode but I'm wondering if there is a "Lisp Interaction" buffer that works with Common Lisp like the *scratch* buffer works with Emacs Lisp. I.E. hitting C-j at the end of a form will insert the result of that form in the current buffer.
I ask because I find editing the output as needed is easier this way than with the repl.
There is M-xslime-scratchRET though I don't
know what does C-j by default because I use
Paredit.
However C-uC-xC-e does what you want in
both *scratch* and *slime-scratch*.
It is bound to C-x C-e.
(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)
Evaluate sexp before point; print value in minibuffer.
Interactively, with prefix argument, print output into current buffer.
Truncates long output according to the value of the variables
`eval-expression-print-length' and `eval-expression-print-level'.
(and it's slime-eval-last-expression in the *slime-scratch* buffer)
Binding this function to C-j does the behaviour that I'm looking for:
(defun slime-eval-print-last-sexp ()
(interactive)
(newline)
(insert (cadr (slime-eval `(swank:eval-and-grab-output ,(slime-last-expression)))))
(newline))

how to stop Emacs from opening new buffers when following a link in customization

The problem occurs when customizing options in Emacs. Every time I click on a link a new buffer is created. How to force Emacs to use single buffer?
Try this:
(defadvice custom-buffer-create (before my-advice-custom-buffer-create)
"Exit the current Customize buffer before creating a new one, unless there are modified widgets."
(if (eq major-mode 'Custom-mode)
(let ((custom-buffer-done-kill t)
(custom-buffer-modified nil))
(mapc (lambda (widget)
(and (not custom-buffer-modified)
(eq (widget-get widget :custom-state) 'modified)
(setq custom-buffer-modified t)))
custom-options)
(if (not custom-buffer-modified)
(Custom-buffer-done)))))
(ad-activate 'custom-buffer-create)
As an alternative to my original answer (which I am not inclined to use myself), I thought I might suggest other ways in which you might deal with getting rid of lots of Customize buffers once you have finished customising things.
First, do note that simply pressing q will "Exit current Custom buffer according to `custom-buffer-done-kill'" (i.e. either bury it or kill it).
Second is to use M-x kill-matching-buffers RET \*Customize RET (and then confirm each one), but that's a bit tedious.
What I'd actually do is use ibuffer.
If you don't use it already, I recommend binding C-x C-b to ibuffer, which is a greatly enhanced alternative to the default list-buffers. I love it primarily for its filtering and grouping abilities, but it can do a great deal besides that.
(global-set-key (kbd "C-x C-b") 'ibuffer)
I also use the advice which can currently be found here at the Emacs Wiki so that ibuffer always opens with the buffer I came from selected.
That done, and from a Customize buffer, C-x C-b * M RET D y will kill all the Customize buffers. That is:
C-x C-b Open ibuffer (with point on the current Customize buffer entry)
* M Mark buffers by major mode...
RET ...select the mode (which defaulted to the major mode of the selected buffer, or otherwise type Custom-mode RET)
D y kill all marked buffers
Try it out; you'll probably like it. Searching for ibuffer will turn up other handy uses.
For instance, you could use / n ^\* RET / g tmp RET to separate out all buffers starting with * into a "tmp" group, so that they don't clutter up the group of buffers you are more likely to be interested in.
As with any major mode, use C-h m to read the built-in documentation.

How can I easily reload Emacs lisp code as I am editing it?

As an Emacs beginner, I am working on writing a minor mode. My current (naive) method of programming elisp consists of making a change, closing out Emacs, restarting Emacs, and observing the change. How can I streamline this process? Is there a command to refresh everything?
You might try using M-C-x (eval-defun), which will re-evaluate the top-level form around point. Unlike M-x eval-buffer or C-x C-e (exal-last-sexp), this will reset variables declared with defvar and defcustom to their initial values, which might be what's tripping you up.
Also try out C-u C-M-x which evaluates the definition at point and sets a breakpoint there, so you get dropped into the debugger when you hit that function.
M-x ielm is also very useful as a more feature-rich Lisp REPL when developing Emacs code.
M-x eval-buffer should do it.
What Sean said. In addition, I have (eval-defun) bound to a key, along with a test. The development loop then becomes: 1) edit function, 2) press eval-and-test key, 3) observe results, 4) repeat. This is extremely fast.
During development I write a test, bind it to jmc-test, then use the above key to run it on my just-edited function. I edit more, then press key again, testing it again. When the function works, I zap jmc-test, edit another function, and write another jmc-test function. They're nearly always one line of code, so easy to just bang out.
(defun jmc-eval-and-test ()
(interactive)
(eval-defun nil)
(jmc-test))
(define-key emacs-lisp-mode-map (kbd "<kp-enter>") 'jmc-eval-and-test)
(when t
(defun myfunc (beer yum)
(+ beer yum))
(defun jmc-test () (message "out: %s" (myfunc 1 2))))
When editing "myfunc", if I hit keypad enter, it prints "out: 3".
It all depends on what you're writing and how you've written it. Toggling the mode should get you the new behavior. If you're using [define-minor-mode][1], you can add code in the body of the macro that keys off the mode variable:
(define-minor-mode my-minor-mode
"doc string"
nil
""
nil
(if my-minor-mode
(progn
;; do something when minor mode is on
)
;; do something when minor mode is off
)
But, another way to check it quickly would be to spawn a new Emacs from your existing one:
M-x shell-command emacs&
I just define a function called ldf (short for load-file) in my .emacs file,
like this:
(defun ldf (arg) (interactive "P") (load-file (buffer-file-name)))
As you can see, this little function looks up the filename of the current buffer and then loads the file. Whenever I need to reload the current buffer elisp file, just type "M-x ldf"