How to get current buffer’s filename in emacs

emacsfunction

One of the main features I miss about Vim, is that it always saves the filename of the current file in the % buffer (more info). That allows launching commands easily like:

;; compile current file
:! gcc %
;; source current file (useful when I'm editing .vimrc
:source %
;; get the size of current file
:! du -sh %
;; etc, etc...

I would like to have similar functionality under emacs (version 24, if that makes any difference), namely have an easy way to insert the name of the file opened in the current buffer.

Examples of what I want to do

Here I describe some basic use cases as to explain better when I feel the need for such a shortcut

  1. Compile: When I enter M-x compile emacs asks me for a compile command. I would like to enter gcc (current-buffer) easily.

  2. Load-file: When I'm editing my .emacs file, I would like to load it right away to test the changes. The way I do it is M-x load-file and then I always spell out the name . e m a c s. I would like to have a shortcut.

  3. Launch outside processes: I gave du -sh as an example, only to illustrate that I want the shortcut to be also available when I execute shell commands with M-!

What I found so far

  • This question here on U&L. The answers given are basically showing where to find the filename of a buffer so one can add it to the kill-ring. It's not exactly what I'm looking for, I don't want to have to manually kill the filename before I want to use it. (Also solutions described in both answers don't seem to work as smoothly in my emacs and require additional keystrokes making them a bit of a pain).

EDIT: A bit unrelated, by I found out why these solutions don't work. I have IDO enabled, for better or worse.

  • The (current-buffer) function described in the manual does return the name of the file in the current buffer, but nowhere in the examples I gave above, am I evaluating elisp code. Is there a way to insert the result of the evaluation of this function in a (mini)buffer and binding this way to a shortcut?

Am I wrong to think this way?

I am currently learning to use emacs (it's been a few months actually) after years of using Vim. I want to avoid a predictable using-emacs-in-a-Vim-way trap. If you feel that what I'm asking for is not very emacs-y, and there should be a better (cleaner?) way to do it, please do mention it in your answers.

Best Answer

You can put a function like follows into your .emacs and bind it to any key you like.

(defun insert-file-name ()
  "Insert the full path file name into the current buffer."
  (interactive)
  (insert (buffer-file-name (window-buffer (minibuffer-selected-window)))))

Also see this question, it seems to be similar.