;; Opens files externally from dired. (defun dired-open-file () "In dired, open the file named on this line." (interactive) (let* ((file (dired-get-filename nil t))) (message "Opening %s" file) (call-process "xdg-open" nil 0 nil file) (message "Opened %s" file))) (eval-after-load "dired" '(define-key dired-mode-map (kbd "C-c o") 'dired-open-file))
in my init file so I can use dired to open PDFs, videos, etc. in applications like Evince or MPV. However, because I'm stupid, I keep hitting RET when wanting to view a PDF or watch a video which then causes Emacs to freeze.
How can I make dired only open files the way it currently does when I hit RET if
xdg-open would open it with Emacs, and otherwise invoke
xdg-open to open the file externally?
Note that I don't always want
xdg-open to be invoked when I hit RET on file because that'd mean a new Emacs instance would be launched every time I open a simple text file via dired.
There is an answer which enables distinction based on the file name extension. This, however, does not work for me as I have many text files without any file name extension but also pictures and PDFs without file name extensions.
xdg-open (and thereby file browsers like Nautilus) manage to open these files using the correct application because
xdg-open can distinguish file type based on their magic numbers.