Emacs Lisp: Open File in External App

, , …,

Here's a simple elisp code that opens 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, ….

Put it in your emacs init file.

(defun ergoemacs-open-in-external-app ()
  "Open the current file or dired marked files in external app."
  (let ( doIt
           ((string-equal major-mode "dired-mode") (dired-get-marked-files))
           (t (list (buffer-file-name))) ) ) )

    (setq doIt (if (<= (length myFileList) 5)
                 (y-or-n-p "Open more than 5 files?") ) )

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

The following shows the file in desktop.

(defun ergoemacs-open-in-desktop ()
  "Show current file in desktop (OS's file manager)."
   ((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.

These commands are part of ErgoEmacs Keybinding.

blog comments powered by Disqus