How to intercept Ctrl-G in Emacs

I have an emisp script for Emacs that I want to do if the user press Ctrl + G. I use read-event to catch all events, but this does not catch Ctrl + G. When you hit Ctrl + G, it just stops execution.

In XEmacs, when you invoke the following event command, it will give you all the events, including when the user press Ctrl + G. Emacs should have some equivalent.

+6
emacs elisp
source share
2 answers

You can use with-local-quit to determine if Cg was pressed:

Edited swallow solution as proposed by efunneko .

 (defun my-cg-test () "test catching control-g" (interactive) (let ((inhibit-quit t)) (unless (with-local-quit (y-or-np "arg you gonna type Cg?") t) (progn (message "you hit Cg") (setq quit-flag nil))))) 

Note: with-local-quit returns the value of the last expression or nil if the Cg button is pressed, so be sure to return something non-zero when Cg not pressed. I found the elisp quitting documentation helpful. The associated area is non-local outputs , and in particular unwind-protect , which applies only to the output.

+11
source share

condition-case and unwind-protect are useful here. condition-case allows you to catch exceptions, of which quit is one:

 (condition-case (while t) ; never terminates (quit (message "Cg was pressed"))) 

You can also catch other errors, for example "error".

unwind-protect as final; he will perform "body forms" and then "unwind forms". However, "unwinding forms" are executed regardless of whether the "body forms" were successfully executed:

 (unwind-protect (while t) (message "Done with infinite loop")) 

You want unwind-protect in your case.

+5
source share