Emacs Lisp: Open File in External App

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

Open File in External App

Here's a emacs command to open the current file or marked dired files in external app. (as if you double-clicked the file on desktop) It's useful for image files, PDF file, video, audio files.

Put it in your emacs init file.

(defun xah-open-in-external-app ()
  "Open the current file or dired marked files in external app.
The app is chosen from your OS's preference.

URL `http://ergoemacs.org/emacs/emacs_dired_open_file_in_ext_apps.html'
Version 2015-01-26"
  (let* (
          (if (string-equal major-mode "dired-mode")
            (list (buffer-file-name))))
         (ξdo-it-p (if (<= (length ξfile-list) 5)
                     (y-or-n-p "Open more than 5 files? "))))

    (when ξdo-it-p
       ((string-equal system-type "windows-nt")
         (lambda (fPath)
           (w32-shell-execute "open" (replace-regexp-in-string "/" "\\" fPath t t))) ξfile-list))
       ((string-equal system-type "darwin")
         (lambda (fPath) (shell-command (format "open \"%s\"" fPath)))  ξfile-list))
       ((string-equal system-type "gnu/linux")
         (lambda (fPath) (let ((process-connection-type nil)) (start-process "" nil "xdg-open" fPath))) ξfile-list))))))

Open File in Desktop

The following shows the file in desktop folder viewer. (Microsoft Windows Explorer, Mac's Finder, Linux's file manager.)

(defun xah-open-in-desktop ()
  "Show current file in desktop (OS's file manager).
URL `http://ergoemacs.org/emacs/emacs_dired_open_file_in_ext_apps.html'
Version 2015-06-12"
   ((string-equal system-type "windows-nt")
    (w32-shell-execute "explore" (replace-regexp-in-string "/" "\\" default-directory t t)))
   ((string-equal system-type "darwin") (shell-command "open ."))
   ((string-equal system-type "gnu/linux")
    (let ((process-connection-type nil)) (start-process "" nil "xdg-open" "."))
    ;; (shell-command "xdg-open .") ;; 2013-02-10 this sometimes froze emacs till the folder is closed. ⁖ with nautilus

You can give it a hotkey, see: Emacs: How to Define Keys.

Like it? Buy Xah Emacs Tutorial.
blog comments powered by Disqus