I'd like to define a key binding that calls a function and inserts some default input in the function's minibuffer prompt. For example, I'd like to call the command ivy-switch-buffer and automatically insert yank "!\*" into the minibuffer.

(note: not really interested in alternative solutions to this particular example; would like a general solution)

  • 2
    IIUC your problem is the same as the one described in this SO question. Note that I have suggested an edit to the accepted answer to use the convenience wrapper macro minibuffer-with-setup-hook instead of minibuffer-setup-hook directly.
    – Basil
    Commented Oct 17, 2017 at 9:57

1 Answer 1


Use minibuffer-setup-hook:

(defun foo () (insert "ABCDE"))

(add-hook 'minibuffer-setup-hook 'foo)

As @Basil mentions in a comment, depending on your use case you can alternatively use macro minibuffer-with-setup-hook (assuming it is available in your Emacs version). It adds a function temporarily to minibuffer-setup-hook, then executes the code in its body. You can use it if you just want a one-off use of a function on the hook.

  (call-interactively #'ivy-switch-buffer))
  • (As @Basil said in a comment to your question, this is the same question as this one on SO. And my answer is the same. In a way it's too bad we cannot deal with questions that are duplicates between different SE sites.))
    – Drew
    Commented Oct 17, 2017 at 13:51
  • 2
    I suggested this edit to your SO answer but it was rejected by a couple of moderators. I'm just curious, is there any reason to prefer manually modifying minibuffer-setup-hook over using the minibuffer-with-setup-hook macro? If not, perhaps you would consider mentioning the latter in your answer here, on the more specialised Emacs SE site.
    – Basil
    Commented Oct 17, 2017 at 13:59
  • @Basil: It's not the same thing. Whether you use it depends on your use case.
    – Drew
    Commented Oct 17, 2017 at 16:52
  • 1
    Indeed and thanks for mentioning it. I see it as analogous to with-current-buffer vs set-buffer: the wrapper macro covers the majority of use-cases (including OP's question) and provides added convenience and safety (e.g. via unwind-protect).
    – Basil
    Commented Oct 17, 2017 at 16:57

Your Answer

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

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