Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy full file path into Copy-Paste-Clipboard

I am looking for a method to save the current full filename of the file I'm working on into my copy-paste buffer to be able to switch to another program and paste e.g. 'C:\some\path\file.txt'.

I have tried the following method but it actually does pretty much nothing:

(defun clip-file ()
  "Put the current file name on the clipboard"
  (interactive)
  (let ((filename (if (equal major-mode 'dired-mode)
                      (file-name-directory default-directory)
                    (buffer-file-name))))
    (when filename
      (x-select-text filename))))

The function x-select-text originates from interprogram-cut-function, which is mentioned in the help file of the Copy-shortcut M-w as a variable containing a function, that is called to save the kill-ring for external programs, so the text may be copy-pasted from Emacs to e.g. Firefox.

I'm using Emacs on my Windows-PC and am therefore not sure, if x-select-text would work, since AFAIK it has something to do with the X-Server from Linux?

like image 316
Peter Wildemann Avatar asked Sep 15 '13 13:09

Peter Wildemann


3 Answers

(defun copy-buffer-file-name-as-kill (choice)
  "Copy the buffer-file-name to the kill-ring"
  (interactive "cCopy Buffer Name (F) Full, (D) Directory, (N) Name")
  (let ((new-kill-string)
        (name (if (eq major-mode 'dired-mode)
                  (dired-get-filename)
                (or (buffer-file-name) ""))))
    (cond ((eq choice ?f)
           (setq new-kill-string name))
          ((eq choice ?d)
           (setq new-kill-string (file-name-directory name)))
          ((eq choice ?n)
           (setq new-kill-string (file-name-nondirectory name)))
          (t (message "Quit")))
    (when new-kill-string
      (message "%s copied" new-kill-string)
      (kill-new new-kill-string))))
like image 104
lawlist Avatar answered Oct 31 '22 16:10

lawlist


I stumbled upon this question when searching for how to copy the file path to clipboard with Spacemacs. So for completeness and to help other people that may also find this question in their searches, notice that Spacemacs has this functionality already binded to:

SPC f y

like image 6
Serafeim Avatar answered Oct 31 '22 18:10

Serafeim


The code mentioned in my question works, it was a problem with my configuration of .emacs-file, because I didn't restart Emacs properly.

Therefore use:

(defun clip-file ()
  "Put the current file name on the clipboard"
  (interactive)
  (let ((filename (if (equal major-mode 'dired-mode)
                      (file-name-directory default-directory)
                    (buffer-file-name))))
    (when filename
      (x-select-text filename))))
like image 4
Peter Wildemann Avatar answered Oct 31 '22 18:10

Peter Wildemann