You can test whether there is an active selection of text using function
C-h f region-active-p tells you:
region-active-p is a compiled Lisp function in
nil if Transient Mark mode is enabled and the mark is active.
Some commands act specially on the region when Transient Mark
mode is enabled. Usually, such commands should use
use-region-p instead of this function, because
also checks the value of
C-h f use-region-p tells you:
use-region-p is a compiled Lisp function in
t if the region is active and it is appropriate to act on it.
This is used by commands that act specially on the region under
Transient Mark mode.
The return value is
t if Transient Mark mode is enabled and the
mark is active; furthermore, if ‘use-empty-active-region’ is
the region must not be empty. Otherwise, the return value is
For some commands, it may be appropriate to ignore the value of
use-empty-active-region; in that case, use
So you would use one of these functions to test whether there is an active selection. If so then you can call
quit (or whatever you want), and if not you can do what you would otherwise normally do.
BTW, it is a good idea to use a named command in a hook, instead of using an anonymous function (aka lambda form). (For one thing, it makes it easier to remove the function from the hook.)