If you're using Emacs 26 or later (unlike what is specified in the question...), you can just use:
(define-key dired-mode-map [mouse-2] 'dired-mouse-find-file)
(The default binding is dired-mouse-find-file-other-window
.)
If you're using Emacs 24 or 25, you'll need to copy the definition of the function, from the Emacs sources (or from this answer — I've copied the definition below, for completeness) into you init.el
. I've tested with Emacs 24.5, and it works.
Definition of dired-mouse-find-file
I've taken the function from here and wrapped it in a check for the version of Emacs, so that if you upgrade to a later Emacs and the definition of the function changes, the stale definition doesn't override the new one.
(when (< emacs-major-version 26)
(defun dired-mouse-find-file (event &optional find-file-func find-dir-func)
"In Dired, visit the file or directory name you click on.
The optional arguments FIND-FILE-FUNC and FIND-DIR-FUNC specify
functions to visit the file and directory, respectively. If
omitted or nil, these arguments default to `find-file' and `dired',
respectively."
(interactive "e")
(or find-file-func (setq find-file-func 'find-file))
(or find-dir-func (setq find-dir-func 'dired))
(let (window pos file)
(save-excursion
(setq window (posn-window (event-end event))
pos (posn-point (event-end event)))
(if (not (windowp window))
(error "No file chosen"))
(set-buffer (window-buffer window))
(goto-char pos)
(setq file (dired-get-file-for-visit)))
(if (file-directory-p file)
(or (and (cdr dired-subdir-alist)
(dired-goto-subdir file))
(progn
(select-window window)
(funcall find-dir-func file)))
(select-window window)
(funcall find-file-func (file-name-sans-versions file t))))))
(For license purposes, the code is under GPLv3+, not under CC BY-SA!)
Explanation
The reason why we're binding mouse-2
rather than mouse-1
, even to specify the action taken when you click on the link with the left mouse button (mouse-1
) is slightly complicated.
Dired specifies (via dired-insert-set-properties
) that in the dired buffer, the name of the file or folder (as opposed to the displayed permissions, name of the owner and other metadata) is a link. In the dired-mode-map, the "key sequence" [follow-link]
is bound to mouse-face
. This means that when you left-click on the link (but not elsewhere), emacs "translates" your left-click to a middle-click (mouse-2
). (For more details, see the manual.)
Consequently, if you want to specify what happens when you left-click on the link, but not elsewhere, you slightly perversely have to change the binding of mouse-2
. You could directly bind to mouse-1
with (define-key dired-mode-map [mouse-1] 'dired-mouse-find-file)
, but that would mean that left-clicking anywhere in the buffer (including in the metadata columns) would cause the corresponding file or directory to be opened.