Reputation: 10155
I use shell-command a lots (default binded to M-!), but often I'm doing stuff to the buffer I'm currently editing. Instead of typing the buffer name (and no filename completion is available in shell-command, alas!), it'd be nice to have a shortcut key, say f3, to insert that name for me whenever I press the key.
The problem is I don't want to bind the key globally (I use f3 for other things in other context), only in minibuffer when shell-command is prompting. It's easy to write a lisp function to insert the current buffer name, but what mode's keymap should I modify to bind a key to that function?
Alternatively, is there any lisp code/package that provide filename completion in shell-command, similar to how bash does it? I know the normal M-x shell does completion, but the convenience of entering a command in minibuffer is hard to give up ;)
Edit:
here is what I wanted, taken from huaiyuan's answer with some fixes inspired by / stolen from http://osdir.com/ml/emacs.sources/2002-04/msg00022.html
(define-key minibuffer-local-map
[f3] (lambda () (interactive)
(insert (buffer-name (current-buffer-not-mini)))))
(defun current-buffer-not-mini ()
"Return current-buffer if current buffer is not the *mini-buffer*
else return buffer before minibuf is activated."
(if (not (window-minibuffer-p)) (current-buffer)
(if (eq (get-lru-window) (next-window))
(window-buffer (previous-window)) (window-buffer (next-window)))))
Upvotes: 20
Views: 5706
Reputation: 26539
(define-key minibuffer-local-map
[f3] (lambda () (interactive) (insert (buffer-name))))
As pointed out in the comment section and elsewhere, the above code snippet doesn't work. (Sorry, I should have tested it before posting. :) Some fixes have been posted; here is another:
(define-key minibuffer-local-map [f3]
(lambda () (interactive)
(insert (buffer-name (window-buffer (minibuffer-selected-window))))))
Regarding filename completion while issuing shell-command
, perhaps this kludge would work (it works for me on Emacs 23.0.60):
(require 'shell)
(define-key minibuffer-local-map (kbd "C-i") 'comint-dynamic-complete)
Upvotes: 11
Reputation: 10984
Here's how to fix huaiyuan's solution:
(define-key minibuffer-local-map [f3]
(lambda() (interactive) (insert (buffer-file-name (nth 1 (buffer-list))))))
You probably should add some sort of error checking in case the "other" buffer has no file name set and (buffer-file-name) returns nil.
Upvotes: 8
Reputation: 101251
I'll defer to huaiyuan about exactly what you asked, but you could also check out Filtering text through a shell command in Emacs as a possible alternative approach.
Upvotes: 2