5

I want to debug my init file, by exiting from loading the file in the middle so if something is wrong after that place it will not be loaded. How can I exit from .emacs file?

jcubic
  • 691
  • 1
  • 4
  • 16
  • 2
    Emacs will exit from your init file immediately once it finds something is wrong, so if you put `(1 + 1)` to the beginning of your init file, the rest will not be loaded at all. is this what you want? BTW, I don't think this method will help you to debug your init file at all. – xuchunyang Jan 09 '16 at 11:23
  • @xuchunyang that help, but I think I used a function that was exiting from the emacs file some time ago when I was debugging init file but I don't remember what function it was. – jcubic Jan 09 '16 at 11:34
  • 1
    You'd be better served by `--debug-init` option you can add when starting Emacs. – wvxvw Jan 09 '16 at 14:29
  • @wvxvw I always have that enabled. – jcubic Jan 09 '16 at 15:55

1 Answers1

9

You can use this to exit from your init file:

(with-current-buffer " *load*"
  (goto-char (point-max)))

Emacs uses the load function to execute lisp file through a temporary buffer, that's " *load*", if the name is not already taken. The above code moves the point to the end of the buffer, thus the read function will not read further code.

For example, the last sexp of foo.el is unbalanced, but there is no error when running it, since Emacs can't go that far, it exits early:

~$ cat foo.el 
(message "Loading %s..." load-file-name)

(with-current-buffer " *load*"
  (goto-char (point-max)))

(this line does not matter
~$ emacs --batch --load foo.el
Loading /home/xcy/foo.el...
~$
xuchunyang
  • 14,302
  • 1
  • 18
  • 39
  • Awesome, thanks. why you have space in the begining of the name of the buffer is it a typo? – jcubic Nov 26 '16 at 17:25
  • 1
    @jcubic No, it isn't. Buffer name starting with a space has a special meaning (see https://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-Names.html if you are interested). – xuchunyang Nov 26 '16 at 17:37
  • It seems like emacs should have a simple `(exit-load)` or `(return)` for this. What if the file is byte-compiled? – NetMage Nov 02 '20 at 23:06
  • @NetMage When loading a byte-compiled file, I get `(error "no buffer named *load*")`. See https://pastebin.com/yQ3PDdJr. – kdb Feb 04 '21 at 09:06
  • For compilation the equivalent buffer would be `" *Compiler Input*"`. – kdb Feb 04 '21 at 09:08