how to answer yes or no automatically in emacs

Viewed 1406

I binded function semantic-symref to key C-c C-r like this:

(global-set-key (kbd "C-c C-r") 'semantic-symref)

everytime I pressed C-c C-r, it prompted:

Find references for xxxxx? (y or n)

How can I answer it automatically? I tryed using lambda function like this, but failed

(global-set-key (kbd "C-c C-r") (lambda() (interactive) (semantic-symref "yes")))

3 Answers

To run a function without prompting for feedback, you can use a macro, this has the advantages that:

  • It doesn't make any global changes to the function (as advice does).
  • Any errors in the code wont lead to the advice being left enabled (although that's preventable using condition-case)
(defmacro without-yes-or-no (&rest body)
  "Override `yes-or-no-p' & `y-or-n-p',
not to prompt for input and return t."
  (declare (indent 1))
  `(cl-letf (((symbol-function 'yes-or-no-p) (lambda (&rest _) t))
             ((symbol-function 'y-or-n-p) (lambda (&rest _) t)))
    ,@body))

This can be bound to a key like this.

(global-set-key (kbd "C-c C-r")
  '(lambda ()
     (interactive)
     (without-yes-or-no
       (semantic-symref))))
Related