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. Open File Path Under Cursor
  2. Copy File Path of Current Buffer
  3. Run Current File
  4. Delete Current File
  5. Backup Current File
  6. Batch Convert Line Ending in Dired
  7. Open File in External App
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.