Using elisp, I call this function (dired "~"), for example, to get to my Home directory in dired mode. When I press RET on one of the files, I want to capture the file path and store it in a variable instead of opening the file.

In other words, if the function dired did actually return the file name of the selected file using RET, I want to do something like this:

(setq file-name (dired "~"))

Where file-name would be the full path of the file that the user selected and pressed RET on.

Any ideas?


Just a little clarification of what I wanted to achieve:

  1. Find the function that will get me the file name from point in a Dired buffer (The answer to that is what @phils said).

  2. Bind RET to store the file name in a variable (The answer to that was provided by @Drew in the comments of @phils answer).



I imagine the function dired-get-filename is what you're looking for?

Or perhaps dired-get-file-for-visit would be more useful (being a wrapper which handles some common errors).

| improve this answer | |
  • Thanks @phills for the quick reply, I've tried something like this: (defun test () (interactive) (dired "~") (setq x (dired-get-filename))) and it seems to work, the variable x does capture the selected filename. However, there's one problem, I have to open the file by pressing RET to get the filename. Is there a way to prevent dired from opening the selected file when pressing RET? I might be using the dired-get-filename function in a wrong way, so maybe you could provide a little code snippet? :D Thanks again. – nasser alshammari Aug 20 '17 at 23:52
  • Based on your comment it is not clear what you are really trying to do. @phils's answer tells you how to set a variable's value to the name of the file at point. Now you are talking about having to press RET to open the file and asking how to not open the file by pressing RET (?). Why are you hitting RET? Please consider clarifying your original question a bit. – Drew Aug 21 '17 at 0:59
  • Are you perhaps asking how to change the key binding of RET in Dired to a command that just puts the file name at point into a variable? – Drew Aug 21 '17 at 1:01
  • Hello @Drew, yes, your last comment is what I want to achieve. When I hit RET I want the file at point to be stored in a variable. Shall I modify the original question? – nasser alshammari Aug 21 '17 at 1:13
  • Yes, please. The answer then is probably to drop the (dired "~") from your command test and bind test to RET in dired-mode-map: (define-key dired-mode-map (kbd "RET") 'test). Once a user is in a Dired buffer, RET will then copy the file name to variable x. Not sure that is a great idea, though. – Drew Aug 21 '17 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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