Emacs: Copy File Path of Current Buffer

By Xah Lee. Date: . Last updated: .

Here's a command to copy the file path of current buffer.

(defun xah-copy-file-path (&optional @dir-path-only-p)
  "Copy the current buffer's file path or dired path to `kill-ring'.
Result is full path.
If `universal-argument' is called first, copy only the dir path.

If in dired, copy the file/dir cursor is on, or marked files.

If a buffer is not file and not dired, copy value of `default-directory' (which is usually the “current” dir when that buffer was created)

URL `http://ergoemacs.org/emacs/emacs_copy_file_path.html'
Version 2017-09-01"
  (interactive "P")
  (let (($fpath
         (if (string-equal major-mode 'dired-mode)
               (let (($result (mapconcat 'identity (dired-get-marked-files) "\n")))
                 (if (equal (length $result) 0)
                     (progn default-directory )
                   (progn $result))))
           (if (buffer-file-name)
             (expand-file-name default-directory)))))
     (if @dir-path-only-p
           (message "Directory path copied: 「%s」" (file-name-directory $fpath))
           (file-name-directory $fpath))
         (message "File path copied: 「%s」" $fpath)
         $fpath )))))

Be sure to give it a easy key. 〔►see Emacs: How to Define Keys

Current File Commands

  1. Emacs: Open File Path Under Cursor
  2. Emacs: Copy File Path of Current Buffer
  3. Emacs: Run Current File
  4. Emacs: Delete Current File
  5. Emacs: Backup Current File
  6. Emacs: Batch Convert Line Ending in Dired
  7. Emacs: Open File in External App
Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.