8

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)

NickD
  • 29,717
  • 3
  • 27
  • 44
yafov
  • 314
  • 1
  • 9
  • 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 Oct 17 '17 at 09:57

1 Answers1

12

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.

(minibuffer-with-setup-hook
    'foo
  (call-interactively #'ivy-switch-buffer))
Drew
  • 77,472
  • 10
  • 114
  • 243
  • (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 Oct 17 '17 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 Oct 17 '17 at 13:59
  • @Basil: It's not the same thing. Whether you use it depends on your use case. – Drew Oct 17 '17 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 Oct 17 '17 at 16:57