12

I want to write a function that will insert the file name of the current buffer into the kill ring so I can yank it to the terminal in another window. How can I programmatically insert a string into the kill ring?

(<SOME FUNCTION> (buffer-file-name))

Is there a (built-in) function for that or do I need to insert the string I want into a buffer and then kill it?

I tried something like this:

(defun path ()
  (interactive)
  (save-excursion
    (let ((begin (mark)))
      (insert (buffer-file-name))
      (kill-region begin (mark)))))

but it doesn't work.

itsjeyd
  • 5,070
  • 2
  • 30
  • 49
jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

22

There's a function for that:

(defun copy-buffer-name ()
  (interactive)
  (kill-new (buffer-file-name)))
abo-abo
  • 20,038
  • 3
  • 50
  • 71
  • 1
    You may prefere ``buffer-name`` instead of ``buffer-file-name``. Because some buffers are not related to a file. – yves Baumes Mar 17 '14 at 12:32
  • @yvesBaumes `buffer-file-name` is fine because I need it only to grab filename. – jcubic Mar 17 '14 at 12:35
  • 2
    @jcubic Then be aware that `(buffer-file-name)` can be `nil`, which would make `kill-new` signal an error. You should guard the expression with `(when (buffer-file-name) …)` –  Mar 17 '14 at 14:06
  • 2
    @lunaryorn Ok, my function is now: `(let ((path (buffer-file-name))) (when path (kill-new path)))` – jcubic Mar 17 '14 at 15:50