2

I am a fiend for C-r (isearch-backward), and I often will enter the minibuffer with M-x (execute-extended-command), then use C-r to search for a previous command. I'd like to bind a key that drops me into the minibuffer to read an extended command and automatically activates isearch-backward, but I'm not sure how to write such a function.

7
  • By default, C-r after M-x searches backward in the minibuffer. It does not "search for a previous command". Perhaps you mean M-r? Or perhaps you have something in your init file that makes Emacs behavior different in this regard? (If so, specify it as part of your question.)
    – Drew
    Oct 12, 2016 at 14:33
  • @Drew For me, with emacs -q, C-r in the M-x prompt does search through command history. I am using emacs 24.3 on this computer, so maybe it's something that changed in recent versions?
    – T. Verron
    Oct 12, 2016 at 15:36
  • @T.Verron: Not here, not on MS Windows. Not with Emacs 20, 22, 23, 24, or 25, including 24.3. Here, C-r after M-x runs Isearch backward.
    – Drew
    Oct 12, 2016 at 17:45
  • @T.Verron: I take that back. I see now, from (emacs) Isearch Minibuffer (and it's true), that if C-r, which is backward Isearch fails when searching the minibuffer text backward, then it searches backward through the input history (likewise, for C-s). M-r just immediately searches backward through the history.
    – Drew
    Oct 12, 2016 at 17:49
  • @Drew I see, I was indeed testing it (and that's probably what the OP does too) with an empty minibuffer, so that the regular search certainly fails.
    – T. Verron
    Oct 12, 2016 at 21:35

1 Answer 1

3

This should help:

(defun my-M-x (arg)
  (interactive "P")
  (minibuffer-with-setup-hook
      (lambda () (call-interactively #'previous-matching-history-element))
    (execute-extended-command arg)))

(global-set-key (kbd "M-x") 'my-M-x)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.