Some commands in Emacs and its various packages are destructive. They require a confirmation by the user. These usually use
yes-or-no-p, which won’t complete the command until the user replies by writing “yes” and then hits enter, or “no”, or aborts the command with C-g.
Some of the commands that require confirmation in this way are overly protective, I find. Like
projectile-kill-buffers (C-p k) which closes all open buffers for a project at once. I use this heavily when e.g. editing my website: jump into the project, edit a file or two, commit, then leave. I don’t want to type “yes” and hit enter just for that. (Please note that killing a buffer this way will still ask me if I want to save or discard changes, so the kill command alone is not destructive.)
There’s a shorter variant of the confirmation,
y-or-n-p, where you only have to hit the “y” or “n” key to select an answer. It’s more like a dialog prompt and less like a conversational chat UI.
Ingenious people on the interwebs figured out that you can temporarily, or rather locally, override the
yes-or-no-p with the shorter
y-or-n-p by using what’s called an “advice”. It’s basically a function decorator. If all you know is Objective-C, think “method swizzling”.
(defun yes-or-no-p->-y-or-n-p (orig-fun &rest r) (cl-letf (((symbol-function 'yes-or-no-p) #'y-or-n-p)) (apply orig-fun r))) (advice-add 'projectile-kill-buffers :around #'yes-or-no-p->-y-or-n-p)
With this code, when I run
projectile-kill-buffers, the actual call (
(apply orig-fun r)) is wrapped in a context where all
yes-or-no-p calls will actually invoke
y-or-n-p. I love it.
Receive new posts via email.