2021-11-13 y-or-n-p but with RET meaning yes

Today, I had an extremely specific need. I wanted the Elisp function y-or-n-p (which asks the user a yes-or-no question, expecting a one-key answer of y or n), but I wanted to interpret RET (or “Enter”) as “yes”. It turns out that by default it means “exit”, which is because y-or-n-p-map has no binding for RET, and y-or-n-p falls back on query-replace-map (in a rather convoluted way). So, here is one way I could change it:

(defconst y-or-n-p-ret-yes-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map y-or-n-p-map)
    (define-key map [return] 'act)
  "A keymap for y-or-n-p with RET meaning \"yes\".")

;; this asks a y/n question with RET meaning "yes"
(let ((y-or-n-p-map y-or-n-p-ret-yes-map))
  (y-or-n-p "yes or no? "))

Notice how we used the dynamic nature of the y-or-n-p-map variable here.

CategoryEnglish, CategoryBlog, CategoryEmacs