Oddbean new post about | logout
 #Emacs tip of the week
Here is a quick tip on how to debug an Emacs command, like when you see an unexpected error message when pressing a key chord that was supposed to run a command: you can use "eval-expression" to get a stack trace (or "backtrace" as Emacs calls it) when an error occurs. Ordinarily when a command fails, especially when run with "M-x" or by pressing a key chord, no stack trace buffer is shown, rather the error is printed to the "*Messages*" buffer. You can set the "debug-on-error" global variable to "t" to force stack traces to pop-up when commands fail, but I find it easier to use the "eval-expression" command instead.

Run "view-lossage, usually bound to "C-h l", this opens a buffer of your most recent key presses and which commands each one executed. Use this to find the name of the command that caused the error.
OR if you are sure which key you pressed that caused the error, use "C-h k <keys> (where <keys> is the key you pressed that caused the error) this will tell you which command should have run when you pressed the key that caused the error.
Run the command again in the same buffer where the error occurred, but instead use "eval-expression", bound to the "M-:" (Alt-Colon) key.
Unlike when using "M-x", you must evaluate the command as a lisp expression in parentheses. At the "Eval:" prompt, type the command name in in parentheses and press enter, for example (this-command-should-work)

Now a "*Backtrace*" buffer will pop up in it's own window and you can start debugging.
Of course, you should be comfortable reading Emacs Lisp code, and understand the basics semantics of Emacs variables, hook functions, and "advice" functions — often times when Emacs breaks it might be because a hook or advice function has been put in place that relies on some global variable that has been changed to an unexpected value.
The greatest strength of Emacs over other editors is that you can easily reprogram any and all aspects of its behavior as you are using it. But this is a double-edged sword, because any mistakes you make in customizing it's behavior can break the thing you were trying to make better. This is especially frustrating when you break a command that is activated by a key binding. You press a key, often times unconsciously because it is committed to muscle memory, and nothing happens but a little error message popping up at the bottom of the window.