1

I'd like to write elisp function with the following functionality:

  1. It can be invoked from the minibuffer, and it will then relate to the latest selected window buffer.
  2. If the selected buffer is in dired-mode, it should insert the file pointed to by dired
  3. Otherwise insert the buffer name of the file

This is what I have got so far:

;; Doesn't work as intended when in minibuffer invoked from dired mode!
(defun get-nondir-filename-from-dired-or-buffer ()
  "Returns either the filename of the buffer or the file pointed to in a dired buffer"
  (interactive)
  (let* ((winbuf (window-buffer (minibuffer-selected-window))))
  (insert
   (shell-quote-argument
    (file-name-nondirectory
     (if (eq (buffer-local-value 'major-mode winbuf)
             'dired-mode)
         (dired-get-filename)  ;; <- How can I get filename from dired?
       (buffer-file-name winbuf)))))))

1

1 Answer 1

1

Found it! I needed to do (save-window-excursion (switch-to-buffer ...) before invoking (dired-get-filename). Here is the final solution:

(defun get-nondir-filename-from-dired-or-buffer ()
  "Returns either the filename of the buffer or the file pointed to in a dired buffer"
  (interactive)
  (let* ((winbuf (window-buffer (minibuffer-selected-window))))
  (insert
   (shell-quote-argument
    (file-name-nondirectory
     (if (eq (buffer-local-value 'major-mode winbuf)
             'dired-mode)
         (save-window-excursion
           (switch-to-buffer winbuf)
           (dired-get-filename))  
       (buffer-file-name winbuf)))))))

For reference, here is a cleaner version, where I have extracted the function to get the buffer or dired filename to a function:

(defun get-referenced-filename ()
  "Get the filename of the buffer or the file pointed to by dired"
  (let* ((winbuf (window-buffer (minibuffer-selected-window))))
    (if (eq (buffer-local-value 'major-mode winbuf)
            'dired-mode)
        (save-window-excursion
          (switch-to-buffer winbuf)
          (dired-get-filename))
      (buffer-file-name winbuf))))

(defun name-of-the-file ()
  "Gets the shell quoted name of the file the current buffer points to"
  (interactive)
  (insert (shell-quote-argument (get-referenced-filename))))

(defun name-nondirectory-of-the-file ()
  "Gets the shell quoted non-directory name of the file the current buffer points to"
  (interactive)
  (insert (shell-quote-argument (file-name-nondirectory (get-referenced-filename)))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.